← Kotlin EspañolChapter 02 of 13

Variables y Tipos de Datos

## Objetivos de Aprendizaje - Comprender las declaraciones val y var - Aprender los tipos de datos básicos de Kotlin - Dominar la inferencia de tipos - Trabajar con tipos anulables ## Variables ### Variables Inmutables (val) Usa `val` para variables que no pueden ser reasignadas: ```kotlin fun main() { val name = "Kotlin" // name = "Java" // Error: Val cannot be reassigned println(name) } ``` ### Variables Mutables (var) Usa `var` para variables que pueden ser cambiadas: ```kotlin fun main() { var count = 0 count = 1 count = 2 println(count) // Output: 2 } ``` ### Cuándo Usar Cuál - Prefiere `val` por defecto para inmutabilidad - Usa `var` solo cuando la reasignación sea necesaria - Los datos inmutables hacen el código más seguro y fácil de razonar ## Tipos de Datos Básicos ### Números ```kotlin fun main() { val byte: Byte = 127 // 8-bit val short: Short = 32767 // 16-bit val int: Int = 2147483647 // 32-bit val long: Long = 9223372036854775807 // 64-bit val float: Float = 3.14f // 32-bit floating point val double: Double = 3.14159 // 64-bit floating point println(byte) println(int) println(float) } ``` ### Caracteres y Cadenas ```kotlin fun main() { val char: Char = 'A' val string: String = "Hello" val multiline = """ This is a multiline string """.trimIndent() println(char) println(string) println(multiline) } ``` ### Booleanos ```kotlin fun main() { val isKotlinFun: Boolean = true val isJavaBetter: Boolean = false println(isKotlinFun) println(!isJavaBetter) // Logical NOT } ``` ### Arreglos ```kotlin fun main() { val numbers = arrayOf(1, 2, 3, 4, 5) val zeros = IntArray(5) // [0, 0, 0, 0, 0] println(numbers[0]) println(numbers.size) } ``` ## Inferencia de Tipos Kotlin puede inferir tipos automáticamente: ```kotlin fun main() { val inferredInt = 42 // Inferred as Int val inferredDouble = 3.14 // Inferred as Double val inferredString = "Hi" // Inferred as String println(inferredInt) println(inferredDouble) println(inferredString) } ``` ## Declaraciones Explícitas de Tipo Cuando la inferencia no es posible, declara los tipos explícitamente: ```kotlin fun main() { val explicitInt: Int = 42 val explicitDouble: Double = 3.14 // Type required when initializing later val laterInit: String laterInit = "Initialized later" println(explicitInt) println(laterInit) } ``` ## Conversión de Tipos Kotlin no soporta ensanchamiento implícito: ```kotlin fun main() { val intVal: Int = 42 // val longVal: Long = intVal // Error: No implicit conversion // Explicit conversion val longVal: Long = intVal.toLong() val doubleVal: Double = intVal.toDouble() println(longVal) println(doubleVal) } ``` ### Funciones de Conversión - `toByte()`, `toShort()`, `toInt()`, `toLong()` - `toFloat()`, `toDouble()` - `toChar()`, `toString()` ## Tipos Anulables El sistema de tipos de Kotlin distingue entre anulables y no anulables: ```kotlin fun main() { var neverNull: String = "This can't be null" // neverNull = null // Error: Null can not be a value of type String var nullable: String? = "This can be null" nullable = null // OK println(nullable) } ``` ### Anulable con Valor Por Defecto Seguro ```kotlin fun main() { var nullable: String? = null // Using safe default with ?: (Elvis operator) val length = nullable?.length ?: 0 println(length) // Output: 0 } ``` ## Verificación de Tipos ```kotlin fun main() { val obj: Any = "Hello" // is operator checks type if (obj is String) { // Smart cast - no explicit cast needed println("Length: ${obj.length}") } // !is for negation if (obj !is Int) { println("Not an Int") } } ``` ### Cast Explícito ```kotlin fun main() { val str: String = "Hello" val obj: Any = str // as operator for explicit casting val casted: String = obj as String println(casted.length) } ``` El cast seguro retorna null en lugar de lanzar excepción: ```kotlin fun main() { val obj: Any = "Hello" // as? returns null if cast fails val casted: Int? = obj as? Int println(casted) // Output: null } ``` ## Plantillas de Cadenas ```kotlin fun main() { val name = "Kotlin" val version = 1.9 println("Language: $name") println("Version: $version") println("Length: ${name.length}") // Expression in template println("Uppercase: ${name.uppercase()}") } ``` ## Resumen - `val` declara variables inmutables, `var` declara variables mutables - Kotlin tiene tipos Int, Long, Double, Float, Boolean, Char, String - La inferencia de tipos determina automáticamente los tipos cuando es posible - Los tipos anulables usan el sufijo `?` (ej., `String?`) - Los casts inteligentes automáticamente hacen cast de tipos después de verificaciones con `is` - `as?` proporciona cast seguro que retorna null en caso de fallo - Las plantillas de cadenas usan `$variable` o `${expresión}`

Comments

Comments powered by Giscus

To enable comments, add your Giscus embed code here.

Learn more about Giscus →