我正在尝试编写函数,它会告诉我字符串很好,很好意味着字符串中至少有一个重复的字母。但是我不能从 lambda 返回,它总是返回 false,尽管 if 语句中的条件通过了。谁能解释一下如何返回?
我试图写 return,但 IDEA 给了我消息 Kotlin: 'return' is not allowed here
fun main(args: Array<String>) {
println("sddfsdf".isNice())
}
fun String.isNice(): Boolean {
val hasRepeat = {
for (i in 0 .. (length - 2)) {
if (subSequence(i, i + 2).toSet().size == 1) {
true
println(subSequence(i, i + 2))
}
}
false
}
return hasRepeat()
}
输出是:
dd
false
最佳答案
您可以标记 lambda,然后使用标记返回:
fun String.isNice(): Boolean {
val hasRepeat = hasRepeat@ {
for (i in 0 .. (length - 2)) {
if (subSequence(i, i + 2).toSet().size == 1) {
return@hasRepeat true
println(subSequence(i, i + 2)) // <-- note that this line is unreachable
}
}
false
}
return hasRepeat()
}
如果你不需要hasRepeat
作为函数引用,你也可以使用命名的本地函数:
fun String.isNice(): Boolean {
fun hasRepeat(): Boolean {
for (i in 0 .. (length - 2)) {
if (subSequence(i, i + 2).toSet().size == 1) {
return true
}
}
return false
}
return hasRepeat()
}
关于kotlin - 从 lambdas 或 Kotlin : 'return' is not allowed here 返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39798269/