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

后端 未结 5 2191
眼角桃花
眼角桃花 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 01:53

    I believe this is due to smart casts used by Kotlin. In other words, Kotlin is able to infer that after this line of code:

    ab = null
    

    type of variable ab is simply null (this is not actual type you can use in Kotlin - I am simply referring to range of allowed values), not String? (in other words, there is no way ab might contain a String).

    Considering that toUpperString() extension function is defined only for Char and String (and not Char? or String?), there is no way to choose between them.

    To avoid this behaviour see answers proposed by other guys (e.g. explicit casting to String?), but this definitely looks like a feature (and quite a useful one) rather than a bug for me.

提交回复
热议问题