gpt4 book ai didi

kotlin - 我在 kotlin 安全调用中遇到重载解析歧义错误

转载 作者:IT老高 更新时间:2023-10-28 13:34:04 31 4
gpt4 key购买 nike

我有一个可为空的字符串变量ab。如果我在将 null 分配给 toUpperCase 后通过安全调用运算符调用它,kotlin 会出错。

fun main(args: Array<String>){
var ab:String? = "hello"
ab = null
println(ab?.toUpperCase())
}

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

这里有什么问题?

最佳答案

doc about smart-casts 中所述:

x = y makes x of the type of y after the assignment

ab = null 行可能智能地将 ab 转换为 Nothing?。如果您检查 ab is Nothing? 确实是 true

var ab: String? = "hello"
ab = null
println(ab?.toUpperCase())
println(ab is Nothing?) // true

由于 Nothing? 是所有类型的子类型(包括 Char?String?),它解释了为什么你会得到 重载解析歧义 错误。此错误的解决方案将是 Willi Mentzel 在 his answer 中提到的。 ,在调用 toUpperCase() 之前将 ab 转换为 String 的类型。


评论:当一个类实现了两个接口(interface)并且两个接口(interface)都具有相同签名的扩展函数时会出现这种错误:

//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 - 我在 kotlin 安全调用中遇到重载解析歧义错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47884934/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com