Compiler Exception: 'Overload resolution ambiguity' despite use of elvis operator

166 views Asked by At

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 ?

1

There are 1 answers

4
enzo On

What types should Kotlin assign to numberOfBooks and s since you didn't provide any type? The solution is to explicitely define the types of your null variables:

fun main(){
  var numberOfBooks: Int? = null
  var s: String? = null
  val l: Int = if (s != null) s.length else -1
  println(l)
  numberOfBooks = numberOfBooks?.dec()?:0
  println(numberOfBooks)
}