从lambdas或Kotlin返回:此处不允许“返回" [英] Return from lambdas or Kotlin: 'return' is not allowed here
问题描述
我正在尝试编写一个函数,该函数将告诉我字符串是不错的,好的意思是字符串在字符串中至少有一个字母重复.但是我无法从lambda进行返回,尽管if语句中的条件通过了,但它总是返回false.有人可以解释一下我如何赚钱吗?
I am trying to write function which will tell me that string is nice, nice means string has at least one repetition of letters in the string. But I can't to make return from lambda, it's always return false, though condition in if statement passed. Can somebody explain me how make return?
我试图写回信,但IDEA给了我消息科特琳:这里不允许'回信'
I have tried to write return, but IDEA gave me the message 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,然后使用标记的return:
You can label lambda and then use labeled return:
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
作为函数引用,则可以使用命名的本地函数:
or you can use named local function, if you do not need hasRepeat
to be function reference:
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()
}
这篇关于从lambdas或Kotlin返回:此处不允许“返回"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!