← Kotlin EspañolChapter 04 of 13

Control de Flujo

## Objetivos de Aprendizaje - Dominar expresiones if - Comprender expresiones when - Trabajar con bucles (for, while, do-while) - Usar rangos e iteraciones ## Expresiones If ### If Básico ```kotlin fun main() { val a = 10 val b = 20 if (a < b) { println("a is less than b") } } ``` ### If-else ```kotlin fun main() { val a = 10 val b = 5 if (a > b) { println("a is greater") } else { println("b is greater or equal") } } ``` ### Cadena If-else-if ```kotlin fun main() { val num = 0 if (num > 0) { println("Positive") } else if (num < 0) { println("Negative") } else { println("Zero") } } ``` ### If como Expresión En Kotlin, if puede retornar un valor: ```kotlin fun main() { val a = 10 val b = 20 val max = if (a > b) a else b println("Max: $max") // 20 } ``` ### Cuerpo de Bloque en Expresión If ```kotlin fun main() { val a = 10 val b = 20 val max = if (a > b) { println("Choosing a") a } else { println("Choosing b") b } println("Max: $max") } ``` ## Expresión When ### When Básico ```kotlin fun main() { val x = 1 when (x) { 1 -> println("One") 2 -> println("Two") 3 -> println("Three") else -> println("Unknown") } } ``` ### When como Expresión ```kotlin fun main() { val x = 2 val result = when (x) { 1 -> "One" 2 -> "Two" 3 -> "Three" else -> "Unknown" } println("Result: $result") } ``` ### Múltiples Valores ```kotlin fun main() { val grade = 'B' val score = when (grade) { 'A' -> 90..100 'B' -> 80..89 'C' -> 70..79 'D' -> 60..69 'F' -> 0..59 else -> null } println("Score range: $score") } ``` ### Usando when sin Argumento ```kotlin fun main() { val num = 15 when { num < 0 -> println("Negative") num == 0 -> println("Zero") num % 2 == 0 -> println("Even positive") else -> println("Odd positive") } } ``` ### Verificación de Tipos con when ```kotlin fun main() { val obj: Any = "Hello" when (obj) { is Int -> println("Integer: ${obj * 2}") is String -> println("String length: ${obj.length}") is Double -> println("Double: ${obj}") else -> println("Unknown type") } } ``` ## Rangos ### Creando Rangos ```kotlin fun main() { // Closed range inclusive val range1 = 1..10 // Downward range val range2 = 10 downTo 1 // With step val range3 = 0..10 step 2 // Until (exclusive end) val range4 = 0 until 10 println(range1) println(range2) println(range3) println(range4) } ``` ### Iterando Sobre Rangos ```kotlin fun main() { println("1..5:") for (i in 1..5) { print("$i ") } println() println("\n5 downTo 1:") for (i in 5 downTo 1) { print("$i ") } println() println("\n0 until 5:") for (i in 0 until 5) { print("$i ") } println() println("\n0..10 step 2:") for (i in 0..10 step 2) { print("$i ") } } ``` ## Bucles For ### Bucle For Básico ```kotlin fun main() { val items = listOf("apple", "banana", "cherry") for (item in items) { println(item) } } ``` ### Bucle For con Índice ```kotlin fun main() { val items = listOf("apple", "banana", "cherry") for (index in items.indices) { println("Item at $index: ${items[index]}") } // Or with withIndex() println() for ((index, value) in items.withIndex()) { println("Item at $index: $value") } } ``` ### Iterando Sobre Mapas ```kotlin fun main() { val map = mapOf("a" to 1, "b" to 2, "c" to 3) for ((key, value) in map) { println("$key -> $value") } } ``` ### Bucle For con Rangos ```kotlin fun main() { // Iterate 0 to 9 for (i in 0 until 10) { print("$i ") } println() // Iterate with step for (i in 0..10 step 2) { print("$i ") } println() // Reverse for (i in 10 downTo 0) { print("$i ") } } ``` ## Bucles While ### While Básico ```kotlin fun main() { var i = 0 while (i < 5) { println("i = $i") i++ } } ``` ### Bucle do-while ```kotlin fun main() { var i = 0 do { println("i = $i") i++ } while (i < 5) } ``` ### While con Break ```kotlin fun main() { var count = 0 while (true) { count++ if (count > 10) { break } } println("Count: $count") } ``` ## Continue ```kotlin fun main() { for (i in 1..10) { if (i % 2 == 0) { continue // Skip even numbers } print("$i ") } println() // Output: 1 3 5 7 9 } ``` ## Bucles Anidados y Etiquetas ### Etiquetas ```kotlin fun main() { outer@ for (i in 1..3) { inner@ for (j in 1..3) { println("i=$i, j=$j") if (i == 2) { break@outer // Break outer loop } } } } ``` ### Continue con Etiquetas ```kotlin fun main() { outer@ for (i in 1..3) { for (j in 1..3) { if (j == 2) { continue@outer } println("i=$i, j=$j") } } } ``` ## Retorno desde Bucles ### Usando return con Etiquetas ```kotlin fun main() { loop@ for (i in 1..10) { for (j in 1..10) { if (i == 2 && j == 2) { println("Found at i=$i, j=$j") break@loop } } } println("Done") } ``` ## Resumen - Las expresiones if pueden retornar valores y son expresiones en Kotlin - When es más poderoso que switch - maneja múltiples valores, rangos, tipos - Usa `..` para rango inclusivo, `until` para final exclusivo - `downTo` crea rangos reversos, `step` cambia el incremento - Los bucles for iteran sobre colecciones, rangos, mapas con índice - Los bucles while y do-while son similares a otros lenguajes - Las etiquetas (`@`) permiten romper/continuar bucles anidados específicos - `break` sale del bucle, `continue` salta a la siguiente iteración

Comments

Comments powered by Giscus

To enable comments, add your Giscus embed code here.

Learn more about Giscus →