3
votes

I saw this question.

How can it be that with this line added

fun Int.toUpperCase() = ""

This problem

Error:(6, 16)
Overload resolution ambiguity:
@InlineOnly public inline fun Char.toUpperCase(): Char defined in kotlin.text
@InlineOnly public inline fun String.toUpperCase(): String defined in kotlin.text

goes away for this piece of code?

fun main(args: Array<String>){
    var ab: String? = "hello"
    ab = null
    println(ab?.toUpperCase())
}

The answer given for the reference question makes sense, it just doesn't answer what is happening here.

1
Indeed, that's some head-scratching material :)Sergio Tulentsev

1 Answers

0
votes

It even works if you define fun String.toUpperCase() = "" in your file again. The compiler chooses the locally defined function to be used and won't consider the ambiguous ones anymore. Since ab becomes Nothing? and this is the subtype of all nullable types, any receiver will make this happen.

Shown here:

fun main(args: Array<String>) {
    println("hello".substringBefore("e"))
}

fun String.substringBefore(e: String) = "hey"

substringBefore from stdlib will not be invoked because the locally defined extension is used.