I have a nullable string variable ab
. If I call toUpperCase
via safe call operator after I assign null to it, kotlin gives error.
fun m
As stated in this doc about smart-casts:
x = y makes x of the type of y after the assignment
The line ab = null
probably smart casts ab
to Nothing?
. If you check ab is Nothing?
it is indeed true
.
var ab: String? = "hello"
ab = null
println(ab?.toUpperCase())
println(ab is Nothing?) // true
Since Nothing?
is subtype of all types (including Char?
and String?
), it explains why you get the Overload resolution ambiguity
error. The solution for this error will be what Willi Mentzel mentioned in his answer, casting ab
to the type of String
before calling toUpperCase()
.
//interface
interface A {}
interface B {}
//extension function
fun A.x() = 0
fun B.x() = 0
//implementing class
class C : A, B {}
C().x() //Overload resolution ambiguity
(C() as A).x() //OK. Call A.x()
(C() as B).x() //OK. Call B.x()