Kotlin Types
Primitive values
In Kotlin source code, numbers, booleans, and characters are all represented as objects with methods—there is no split between int and Integer like in Java. At compile time, the Kotlin compiler lowers non-nullable numbers (Int, Long, Double, Boolean) to JVM primitives for performance, and you must convert between numeric types explicitly (for example, count.toDouble()) rather than relying on silent widening:
val count: Int = 3
val bigId = 10_000_000L // underscores improve readability; L marks Long
val price = 19.99 // inferred as Double
val active = true
// Explicit conversion prevents accidental precision loss
val total = count.toDouble() * price
Strings
Kotlin strings are immutable sequences of UTF-16 characters. Use string templates ($variable or ${expression}) instead of + concatenation, and triple-quoted raw strings ("""...""") with .trimIndent() for multi-line SQL, JSON, or log templates without escape clutter:
val user = "Ada"
val banner = """
|Welcome, $user
|Items in cart: ${1 + 2}
""".trimMargin()
Arrays and values
Kotlin distinguishes fixed-size arrays (Array<T> or primitive-backed IntArray) from read-only and mutable collections. In day-to-day application code, prefer listOf(...) over arrayOf(...) because List has structural equality (== compares contents) and a rich immutable API, whereas arrays compare by reference:
val numbers = intArrayOf(1, 2, 3) // unboxed JVM int[] for tight loops
val names = listOf("Ada", "Linus") // read-only List<String>
println(names == listOf("Ada", "Linus")) // true (structural equality)
Type inference
The compiler infers local variable types from their initializer, keeping code concise without losing static checks. However, always write explicit types on public function return types, exported properties, and numeric constants where Int vs. Long or Float vs. Double matters for API compatibility.
Practice
Test Kotlin's type rules and string formatting in a short snippet:
- Declare an
Intand aDouble, multiply them using explicit conversion, and print the result. - Build a multi-line raw string with
trimIndent()and an interpolated expression inside${...}. - Compare two equal
listOf(...)instances with==versus twoarrayOf(...)instances and observe the difference.