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

后端 未结 5 2184
眼角桃花
眼角桃花 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:55

    It really seems like a bug. The type String? is lost somehow upon assigning null, so you have to tell the compiler explicitely that it should deal with a String?.

    fun main(args: Array){
        var ab: String? = "hello"
        ab = null
        println((ab as String?)?.toUpperCase()) // explicit cast
    
        // ...or
    
        println(ab?.let { it.toUpperCase() }) // use let
    }
    

提交回复
热议问题