gpt4 book ai didi

kotlin - kotlin “when”的 “startWith”出现编译错误

转载 作者:行者123 更新时间:2023-12-02 10:47:39 25 4
gpt4 key购买 nike

我对Kotlin不满意(尽管我在Java等其他语言方面有很多经验)。我试图用Kotlin编写一些代码,但不明白为什么以下代码无法编译。

private fun test(inpStr : String) =
when (inpStr) {
"bill" -> "harry"
startsWith "john" -> "john"
else -> inpStr
}

确实会编译以下内容:
private fun test2(inpStr : String) =
when {
inpStr == "bill" -> "harry"
inpStr.startsWith("john") -> "john"
else -> inpStr
}

根据我对“何时”的理解,我会认为它们既可以编译也可以等效。我收到的错误消息在“startsWith”行上:
 Unresolved reference. None of the following candidates is applicable because of receiver type mismatch:
public fun File.startsWith(other: File): Boolean defined in kotlin.io
public fun File.startsWith(other: String): Boolean defined in kotlin.io
public fun CharSequence.startsWith(char: Char, ignoreCase: Boolean = ...): Boolean defined in kotlin.text
public fun CharSequence.startsWith(prefix: CharSequence, ignoreCase: Boolean = ...): Boolean defined in kotlin.text
public fun CharSequence.startsWith(prefix: CharSequence, startIndex: Int, ignoreCase: Boolean = ...): Boolean defined in kotlin.text
public fun String.startsWith(prefix: String, ignoreCase: Boolean = ...): Boolean defined in kotlin.text

有什么想法吗?

最佳答案

when (inpStr)具有(!)is ...(!)in ...else的特殊规则。
startsWith "john"并不是其中之一,因此它被假定为完整的表达式,就像"bill"一样;它将被计算,然后与inpString进行比较。
如您所料,没有转换为inpStr.startsWith("john")

关于kotlin - kotlin “when”的 “startWith”出现编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59128594/

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