Kotlin Data Types
Kotlin's built-in types describe the exact shape of the data your variables can hold, from whole numbers to text.
Kotlin's Basic Types
Every value in Kotlin has a type, and the compiler uses that type to check which operations are valid. The four types you will use constantly are Int, Double, String, and Boolean, alongside the single-character Char type.
Numbers: Int and Double
Int and Double in action
fun main() {
val itemCount: Int = 12
val unitPrice: Double = 4.99
val total = itemCount * unitPrice
println("Total price: $total")
}Text: String and Char
String and Char basics
fun main() {
val grade: Char = 'A'
val message: String = "You scored grade $grade"
println(message)
println("First character: ${message[0]}")
}Char values are always wrapped in single quotes and hold exactly one character, while String values use double quotes and can hold any amount of text, including an empty string. Strings in Kotlin are indexed like arrays, so message[0] gives you the first character.
- Byte: 8 bits, range -128 to 127
- Short: 16 bits, range -32768 to 32767
- Int: 32 bits, the default type for whole number literals
- Long: 64 bits, used for very large numbers and must be suffixed with L, e.g. 10000000000L
- Float: 32-bit decimal, suffixed with f
- Double: 64-bit decimal, the default type for decimal literals
Boolean values and runtime type checks
fun main() {
val isActive: Boolean = true
val age = 30 // inferred as Int
val weight = 62.5 // inferred as Double
println("Active: $isActive, Age: $age, Weight: $weight")
println("age is Int? ${age is Int}")
}Note: Tip: When a whole number needs to exceed about 2.1 billion, switch from Int to Long and add the L suffix to its literal, otherwise Kotlin will report the value as out of range.
Note: Watch out: Mixing Int and Double in the same expression, like 5 / 2 versus 5.0 / 2, gives very different results. Integer division truncates to 2, while the Double version correctly returns 2.5.
Exercise: Kotlin Data Types
What type does a decimal literal like 19.99 default to?