Café y Código

2. Variables y tipos: Contenedores de datos

val vs var: Inmutabilidad primero

Kotlin distingue claramente entre lo que puede cambiar y lo que no:

  • val: constante, no se puede reasignar (preferí usar val siempre).
  • var: mutable, puede reasignarse.
val-vs-var.kt
KOTLIN
1 val nombre = "Kotlin" // inmutable
2 // nombre = "Java" // ERROR: no se puede reasignar
3
4 var edad = 25 // mutable
5 edad = 26 // OK: se puede reasignar
6 println(edad)

Tipos de datos básicos

Kotlin es estáticamente tipado, pero infiere el tipo automáticamente:

tipos.kt
KOTLIN
1 val entero: Int = 42
2 val decimal: Double = 3.14
3 val texto: String = "Hola"
4 val activo: Boolean = true
5
6 // Kotlin infiere el tipo:
7 valAutomatico = 100 // Int
8 val tambienAutomatico = "Texto" // String

Conversión de tipos

A diferencia de Java, Kotlin no hace casting implícito. Debes ser explícito:

conversiones.kt
KOTLIN
1 val numero: Int = 42
2 val decimal: Double = numero.toDouble() // Int → Double
3 val texto: String = numero.toString() // Int → String
4 val desdeTexto: Int = "100".toInt() // String → Int
5
6 println(decimal) // 42.0
7 println(texto) // "42"
8 println(desdeTexto) // 100

💻 Misión

Declara variables de cada tipo (Int, Double, String, Boolean) e imprímelas con println(). Luego convierte un Int a String y un Double a Int.

👁️ Ver solución sugerida
main.kt
KOTLIN
1 fun main() {
2 val edad: Int = 28
3 val precio: Double = 19.99
4 val nombre: String = "Ana"
5 val activo: Boolean = true
6
7 println(edad)
8 println(precio)
9 println(nombre)
10 println(activo)
11
12 val edadTexto = edad.toString()
13 val precioEntero = precio.toInt()
14 println("Edad como texto: $edadTexto")
15 println("Precio como entero: $precioEntero")
16 }

Pon a prueba tus variables

Ko-fi
Donaciones
Apoyá cafeycodigo con un café en Ko-fi. Colaboradores: insignia, muro y zona exclusiva.