gpt4 book ai didi

android - 无法在 kotlin `when` 表达式中使用 string.contains()

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

我是 kotlin 的新手,我尝试了几种使用以下代码的方法

val strAction = "Grid"
when(strAction){
strAction.contains("Grid")->println("position is 1")
}

在上面的代码中 strAction.contains("Grid") 这行向我显示了不兼容类型的错误

enter image description here

最佳答案

您还可以将 whenwith 结合使用以获得良好的语法:

with(strAction) {
when {
contains("Grid") -> println("position is 1")
contains("bar") -> println("foo")
startsWith("foo") -> println("bar")
else -> println("foobar")
}
}

您也可以将 when 的结果保存到属性中:

val result = with(strAction) {
when {
contains("bar") -> "foo"
startsWith("foo") -> "bar"
else -> "foobar"
}
}

println(result)

关于android - 无法在 kotlin `when` 表达式中使用 string.contains(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47434438/

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