本文介绍了我在Kotlin安全通话上收到了过载分辨率歧义错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个可为空的字符串变量ab.如果我在为null赋值后通过安全呼叫运算符呼叫toUpperCase,则kotlin会给出错误消息.

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 main(args: Array<String>){
    var ab:String? = "hello"
    ab = null
    println(ab?.toUpperCase())
}

这是什么问题?

推荐答案

有关智能广播的文档:

ab = null可能很聪明,将ab强制转换为Nothing?.如果您选择ab is Nothing?,则确实是true.

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

由于Nothing?是所有类型的子类型(包括Char?String?),因此它说明了为什么出现Overload resolution ambiguity错误的原因.解决此错误的方法将是Willi Mentzel在他的答案中提到的内容,将ab强制转换为String在调用toUpperCase()之前.


评论:当一个类实现两个接口并且两个接口都具有相同签名的扩展功能时,会发生这种错误:

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

这篇关于我在Kotlin安全通话上收到了过载分辨率歧义错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 11:16