Basic Types and Type Inference
Kotlin's core types and how the compiler figures out most of them without annotations.
អាន 2 នាទី
Kotlin is statically typed — every value has a known type at compile time — but you rarely have to write those types out. The compiler infers them from context, a feature called type inference.
val age = 30 // inferred as Int
val price = 19.99 // inferred as Double
val initial = 'K' // inferred as Char
val isActive = true // inferred as Boolean
val name = "Alice" // inferred as StringEach of these could be written with an explicit type annotation — val age: Int = 30 — and sometimes you should, for clarity in a public API or when the inferred type isn't obvious. But for local variables with an obvious initializer, inference keeps the code readable without losing type safety: age is still genuinely an Int, the compiler just didn't make you say so.
The numeric types
Kotlin has several numeric types, distinguished by size and whether they hold whole numbers or decimals:
val small: Byte = 127
val short: Short = 30_000
val standard: Int = 2_000_000
val big: Long = 3_000_000_000L // note the L suffix
val precise: Double = 3.14159
val single: Float = 3.14f // note the f suffixInt and Double cover the vast majority of everyday code. The underscore in 2_000_000 is just a readability separator — it has no effect on the value, similar to a comma in written numbers.
No automatic widening
Unlike some languages, Kotlin will not silently convert between numeric types for you, even when it looks safe:
val whole: Int = 10
val decimal: Double = whole // Compile error: type mismatch
val decimal: Double = whole.toDouble() // correctThis is deliberate. An implicit Int → Double conversion is harmless, but an implicit Long → Int conversion can silently truncate a value — Kotlin would rather you convert explicitly everywhere, using functions like .toInt(), .toDouble(), or .toLong(), so a truncating conversion is always visible in the code.
Booleans and characters
val isPublished: Boolean = true
val grade: Char = 'A'
if (isPublished && grade == 'A') {
println("Ready to ship")
}Char holds a single character in single quotes — 'A', not "A". Double quotes are reserved for String.
Everything is an object
Even Int and Boolean are objects in Kotlin, not raw primitives like in Java — they have methods you can call directly:
println(5.coerceAtLeast(10)) // 10
println((-7).absoluteValue) // 7
println("Kotlin".length) // 6Under the hood, the compiler still compiles simple numeric types down to JVM primitives for performance where it can — you get object-like ergonomics without paying a runtime cost for it.
Next up: string templates, which build on these types to make constructing text far less painful than manual concatenation.