2016-09-30 37 views
11

我想寫的函數會告訴我,字符串很好,nice意味着字符串中至少有一個字母重複的字符串。但我不能從lambda返回,它總是返回false,儘管if語句中的條件通過。有人能解釋我如何回報?從lambdas或Kotlin返回:'返回'是不允許在這裏

我試圖寫回,但IDEA給我的消息科特林: '迴歸' 這裏不允許使用

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 

回答

15

你可以標記拉姆達然後用標記的回報:

fun String.isNice(): Boolean { 
    val hasRepeat = [email protected] { 
     for (i in 0 .. (length - 2)) { 
      if (subSequence(i, i + 2).toSet().size == 1) { 
       [email protected] 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() 
} 
+0

謝謝,你的回答也給了我一些關於這個問題的額外解釋。 –

7

你不能做一個non-local return在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() 
} 
+0

謝謝,但它只是例子,我知道,我可以將此函數放在isNice()級別上,無論如何,謝謝。 –

+0

明白了。我已經更新了我的答案,以刪除不必要的簡化示例。 – mfulton26

相關問題