kotlin - 从 lambdas 或 Kotlin : 'return' is not allo

我正在尝试编写函数,它会告诉我字符串很好,很好意味着字符串中至少有一个重复的字母。但是我不能从 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/

相关文章:

kotlin - 为什么这个 Kotlin 方法有封闭的反引号?

kotlin - 如何在一行上声明多个属性

kotlin - 从 Kotlin 中的密封类扩展数据类

android - 使用 Retrofit 方法更具表现力

android - 使用 Kotlin 组合整数标志的最佳方法?

kotlin - 做任何==对象

android - Kotlin 错误 : Dagger does not support inje

android - 从 Activity Kotlin 中获取额外的字符串

android - 使用 Kotlin 关闭/隐藏 Android 软键盘

kotlin - 如何在 Kotlin 中定义非序数枚举?