
class ControlFlow {
private fun showCase1() {
//If
val num1 = 5
val num2 = 10
if (num1 > num2) {
Log.w("CONTROL-FLOW-1", "NUM1 es mayor que NUM2")
}
if (num2 > num1) {
Log.w("CONTROL-FLOW-1", "NUM2 es mayor que NUM1")
}
}
private fun showCase2() {
//If Else
val num1 = 5
val num2 = 10
if (num1 > num2) {
Log.w("CONTROL-FLOW-2", "NUM1 es mayor que NUM2")
} else {
Log.w("CONTROL-FLOW-2", "NUM2 es mayor que NUM1")
}
//Como expresion
if (num1 > num2) Log.w("CONTROL-FLOW-2", "NUM1 es mayor que NUM2") else Log.w("CONTROL-FLOW-1", "NUM2 es mayor que NUM1")
val result = if (num1 > num2) num1 else num2
}
private fun showCase3() {
//When (switch en Java)
val x = 1
//Con Argumentos(x)
when (x) {
1 -> Log.w("CONTROL-FLOW-3", "x==1")//case 1
2 -> Log.w("CONTROL-FLOW-3", "x==2")//case 2
else -> Log.w("CONTROL-FLOW-3", "X es otro número") // Case Default, NO es obligatorio
}
when (x) {
0, 1 -> Log.w("CONTROL-FLOW-3", "x==0 ó x==1")// Agrupamiento. Case 0 ó 1
}
// Sin Argumento, se hace una operación donde iría el caso.
when {
(x % 2 == 0) -> Log.w("CONTROL-FLOW-3", "El numero es Par")
(x % 2 == 1) -> Log.w("CONTROL-FLOW-3", "El numero es Impar")
}
//Sin Argumento y Devolviendo un Valor
val esPar = when {
(x % 2 == 0) -> true
else -> false
}
}
private fun showCase4() {
//Bucles For
val numbers = arrayOf(1, 2, 3, 4, 5)
for (number in numbers) Log.w("CONTROL-FLOW-4", number.toString())
//Especificando el tipo
for (number: Int in numbers) Log.w("CONTROL-FLOW-4", number.toString())
//Con Indices
for ((index, number) in numbers.withIndex()) { // withIndex() devuelve el valor y el indice
Log.w("CONTROL-FLOW-4", "$index: $number")
}
}
private fun showCase5() {
//While
var x = 10
while (x > 0) {
Log.w("CONTROL-FLOW-5", x--.toString()) //Hacemos la operación de restar junto con la impresión
}
// Do While
do {
Log.w("CONTROL-FLOW-5", "1º y única iteracion")
} while (x > 0)
}
fun showCases() {
showCase1()
showCase2()
showCase3()
showCase4()
showCase5()
}
}
Documentación Oficial