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

标签 kotlin compiler-errors

我对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/

相关文章:

Kotlin map : why is there no toHashMap()?

java - 是否可以为 kotlin 中的内部委托(delegate)属性提供自定义名称?

compiler-errors - 错误: no newline at end of file [-Werror,-Wnewline-eof]#endif when apportable load work on my IOS Game

regex - 正则表达式的 Kotlin 性能问题

gradle - 如何将依赖项添加到我的自定义 Gradle 插件?

java - RxJava 与 Single.zip 中嵌套的 Single.flatMap 相同吗?

c# - C#Python输入法返回错误

.net - 使用 @Html.ActionLink() 时出错

templates - C++11 MSVS vs GCC 静态成员初始化中模板参数名称的可见性

java - 在netbeans中打开新jFrame的按钮不起作用