Kotlin вернуться, сломать, продолжить Ключевые слова

Kotlin возврат, перерыв, продолжение Ключевые слова

1. обзор

В этом руководстве мы обсудим использование выражений структурного перехода в Kotlin.

Проще говоря,Kotlin has three structural jump expressions: return, break, continue.. В следующих разделах мы рассмотрим их функции с ярлыком и без него.

2. Этикетки в Котлине

Любые выражения в Kotlin могут быть помечены меткой.

We create a label by using an identifier followed by the “@” sign. Например,[email protected],[email protected] - допустимые метки.

Чтобы пометить выражение, мы просто добавляем метку перед ним:

[email protected] for (i in 1..10) {
    // some code
}

3. ЗаявлениеBreak

Без меткиbreak завершает ближайший охватывающий цикл.

Давайте посмотрим на пример:

@Test
fun givenLoop_whenBreak_thenComplete() {
    var value = ""
    for (i in "hello_world") {
        if (i == '_') break
        value += i.toString()
    }
    assertEquals("hello", value)
}

В качестве альтернативы мы можем использоватьbreak with a label, which terminates the loop marked with that label:

@Test
fun givenLoop_whenBreakWithLabel_thenComplete() {
    var value = ""
    [email protected] for (i in 'a'..'d') {
        for (j in 1..3) {
            value += "" + i + j
            if (i == 'b' && j == 1)
                [email protected]_loop
        }
    }
    assertEquals("a1a2a3b1", value)
}

В этом случае внешний цикл завершается, когда переменныеi иj равны «b» и «1» соответственно.

4. ЗаявлениеContinue

Затем давайте взглянем на ключевое словоcontinue, которое мы также можем использовать с ярлыком или без него.

Без меткиcontinue перейдет к следующей итерации охватывающего цикла:

@Test
fun givenLoop_whenContinue_thenComplete() {
    var result = ""
    for (i in "hello_world") {
        if (i == '_') continue
        result += i
    }
    assertEquals("helloworld", result)
}

С другой стороны,when we use continue with a label marking a loop, it will proceed to the next iteration of that loop:

@Test
fun givenLoop_whenContinueWithLabel_thenComplete() {
    var result = ""
    [email protected] for (i in 'a'..'c') {
        for (j in 1..3) {
            if (i == 'b') [email protected]_loop
            result += "" + i + j
        }
    }
    assertEquals("a1a2a3c1c2c3", result)
}

В этом примере мы использовалиcontinue, чтобы пропустить одну итерацию цикла с меткойouter_loop..

5. ЗаявлениеReturn

Без метки этоreturns to the nearest enclosing function or anonymous function:

@Test
fun givenLambda_whenReturn_thenComplete() {
    var result = returnInLambda();
    assertEquals("hello", result)
}

private fun returnInLambda(): String {
    var result = ""
    "hello_world".forEach {
        if (it == '_') return result
        result += it.toString()
    }
    //this line won't be reached
    return result;
}

Return также полезен, когда мы хотимapply continue logic on anonymousfunctions:

@Test
fun givenAnonymousFunction_return_thenComplete() {
    var result = ""
    "hello_world".forEach(fun(element) {
        if (element == '_') return
        result += element.toString()
    })
    assertEquals("helloworld", result)
}

В этом примере операторreturn вернется к вызывающему анонимного развлечения, т.е. циклforEach.

In the case of a lambda expression, we can also use return with a label для достижения аналогичного результата:

@Test
fun givenLambda_whenReturnWithExplicitLabel_thenComplete() {
    var result = ""
    "hello_world".forEach [email protected]{
        if (it == '_') {
            [email protected]
        }
        result += it.toString()
    }
    assertEquals("helloworld", result)
}

В качестве альтернативы мы также можемreturn using an implicit label:

@Test
fun givenLambda_whenReturnWithImplicitLabel_thenComplete() {
    var result = ""
    "hello_world".forEach {
        if (it == '_') {
            // local return to the caller of the lambda, i.e. the forEach loop
            [email protected]
        }
        result += it.toString()
    }
    assertEquals("helloworld", result)
}

В приведенном выше примере оператор return также вернется к вызывающему лямбда-выражению - циклуforEach.

Наконец,return можно использовать с меткойapply break logic to lambda expressions byreturning to a label outside:

@Test
fun givenAnonymousFunction_returnToLabel_thenComplete() {
    var result = ""
    run [email protected]{
        "hello_world".forEach {
            if (it == '_') [email protected]
            result += it.toString()
        }
    }
    assertEquals("hello", result)
}

6. Заключение

В этой статье мы рассмотрели варианты использованияreturn, break, continue в Kotlin.

Пример кода можно найтиover on Github.