Kotlin Data Types
A data type is the kind of a stored value. Kotlin has types for whole numbers, decimal numbers, text, truth values, and single characters.
One value of each type
Five values sit in five names, and each value has a different type. The letter wears single quotes because a Char holds one character.
fun main() {
val whole = 4
val price = 2.5
val word = "cup"
val ready = true
val letter = 'A'
println(whole)
println(price)
println(word)
println(ready)
println(letter)
}Writing types beside names
The score line carries an Int annotation beside its name. The label line carries a String annotation beside its name.
fun main() {
val score: Int = 12
val label: String = "Points"
println(label)
println(score)
}A type picked from the value
No annotation sits beside count in this code. The value 8 is a whole number, so the type of count is Int.
fun main() {
val count = 8
println(count)
}A mismatched annotation fails
The annotation asks for a String and the value is a whole number. The compiler stops at that mismatch.
fun main() {
val name: String = 42
println(name)
}Example
fun main() {
val age: Int = 20
val height = 1.8
val city: String = "York"
val member = true
val initial: Char = 'Y'
println(age)
println(height)
println(city)
println(member)
println(initial)
}Key points
- Int: a whole number type.
- Double: a number type with a decimal part.
- String: a text type.
- Boolean: a type with the two values true and false.
- Char: a type for one single character.
- Use a type annotation to write a type after a colon beside a name.
- Type inference: the type follows from the value when no annotation is written.
In this example, age has the annotation Int and the value 20. height holds 1.8 with no annotation, so its type follows from the value. city has the annotation String and the value York. member holds true with no annotation. initial has the annotation Char and the single character Y. The println lines show the five values in that order.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Kotlin Playground
Exercise
Which type holds the values true and false?