Return from lambdas or Kotlin: 'return' is not allowed here
Solution 1:
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()
}
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()
}
Solution 2:
You cannot do a non-local return inside a lambda but you can change your lambda to an anonymous function:
fun String.isNice(): Boolean {
val hasRepeat = fun(): Boolean {
for (i in 0..(length - 2)) {
if (subSequence(i, i + 2).toSet().size == 1) {
return true
}
}
return false
}
return hasRepeat()
}