The following snippet causes the compiler to throw an exception:
fun main(){
var numberOfBooks = null
var s = null
val l: Int = if (s != null) s.length else -1
println(l)
numberOfBooks = numberOfBooks?.dec()?:0 // this should default to 0
println(numberOfBooks)
}
Giving the exceptions
Unresolved reference: length
Type mismatch: inferred type is IntegerLiteralType[Int,Long,Byte,Short] but Nothing? was expected
Type mismatch: inferred type is IntegerLiteralType[Int,Long,Byte,Short] but Nothing? was expected
Overload resolution ambiguity: public inline operator fun BigDecimal.dec(): BigDecimal defined in kotlin public inline operator fun BigInteger.dec(): BigInteger defined in kotlin
I thought the elvis operator would handle null. Where did I go wrong ?
What types should Kotlin assign to
numberOfBooksandssince you didn't provide any type? The solution is to explicitely define the types of yournullvariables: