我在Kotlin安全通话上收到了过载分辨率歧义错误 [英] I'm getting Overload resolution ambiguity error on kotlin safe call
问题描述
我有一个可为空的字符串变量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())
}
错误:(6,16)
重载解析度不明确:
@InlineOnly仅公开 内联乐趣Char.toUpperCase():在kotlin.text
中定义的Char @InlineOnly public inline fun String.toUpperCase():在kotlin.text中定义的字符串
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
这是什么问题?
推荐答案
x = y使赋值后的x成为y的类型
x = y makes x of the type of y after the assignment
行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安全通话上收到了过载分辨率歧义错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!