我正在尝试写函数,它会告诉我字符串很好,很好意味着字符串在字符串中至少有一个重复的字母.但我无法从lambda返回,它总是返回false,尽管if语句中的条件已经过去了.有人能解释我怎么回报?
我试着写回报,但是IDEA给了我Kotlin的消息:这里不允许'返回'
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()
}
Run Code Online (Sandbox Code Playgroud)
输出是:
dd
false
Run Code Online (Sandbox Code Playgroud)
Ily*_*lya 37
你可以标记lambda,然后使用带标签的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()
}
Run Code Online (Sandbox Code Playgroud)
或者你可以使用命名本地函数,如果你不需要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()
}
Run Code Online (Sandbox Code Playgroud)
mfu*_*n26 10
你不能在lambda中进行非本地返回,但你可以将lambda更改为匿名函数:
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()
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10507 次 |
| 最近记录: |