I'm getting Overload resolution ambiguity error on kotlin safe call

后端 未结 5 2160
眼角桃花
眼角桃花 2021-02-20 01:27

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         


        
5条回答
  •  有刺的猬
    2021-02-20 02:15

    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().


    Remarks: This kind of error will occur when a class implements two interfaces and both interface have extension function of the same signature:

    //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()
    

提交回复
热议问题