Kotlin retorna, quebra, continua

Kotlin retorna, quebra, continua

1. Visão geral

Neste tutorial, discutiremos o uso de expressões de salto estrutural no Kotlin.

Simplificando,Kotlin has three structural jump expressions: return, break, continue. Nas próximas seções, vamos cobrir suas funcionalidades com e sem um rótulo.

2. Etiquetas em Kotlin

Quaisquer expressões no Kotlin podem ser marcadas com um rótulo.

We create a label by using an identifier followed by the “@” sign. Por exemplo,[email protected],[email protected] são rótulos válidos.

Para rotular uma expressão, basta adicionar o rótulo à sua frente:

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

3. A declaraçãoBreak

Sem um rótulo,break termina o loop envolvente mais próximo.

Vamos dar uma olhada em um exemplo:

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

Alternativamente, podemos usarbreak 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)
}

Nesse caso, o loop externo é encerrado quando as variáveisiej são iguais a “b” e “1”, respectivamente.

4. A declaraçãoContinue

A seguir, vamos dar uma olhada na palavra-chavecontinue, que também podemos usar com ou sem um rótulo.

Sem um rótulo,continue irá prosseguir para a próxima iteração do loop envolvente:

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

Por outro lado,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)
}

Neste exemplo, usamoscontinue para pular uma iteração do loop rotulado comoouter_loop.

5. A declaraçãoReturn

Sem um rótulo, é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 também é útil quando queremosapply 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)
}

Neste exemplo, a instruçãoreturn retornará ao chamador da diversão anônima, ou seja, o loopforEach.

In the case of a lambda expression, we can also use return with a label para obter um resultado semelhante:

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

Alternativamente, também podemosreturn 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)
}

No exemplo acima, a instrução de retorno também retornará ao chamador do lambda - o loopforEach.

Finalmente,return pode ser usado com um rótulo paraapply 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. Conclusão

Neste artigo, examinamos os casos de uso dereturn, break, continue em Kotlin.

O código de amostra pode ser encontradoover on Github.