Return from lambdas or Kotlin: 'return' is not allowed here

Kotlin

Kotlin Problem Overview


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?

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()
}

ouput is:

dd
false

Kotlin Solutions


Solution 1 - Kotlin

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 - Kotlin

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()
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSergey LuchkoView Question on Stackoverflow
Solution 1 - KotlinIlyaView Answer on Stackoverflow
Solution 2 - Kotlinmfulton26View Answer on Stackoverflow