Basic Types and Type Inference
Prerequisites: Variables: val and var
Every value in Kotlin has a type, which decides what you can do with it. The basic types:
| Type | Example | Used for |
|---|---|---|
Int |
42, -7 |
Whole numbers (up to about 2.1 billion) |
Long |
42L |
Larger whole numbers |
Double |
3.14 |
Numbers with a decimal point |
Float |
3.14f |
Less precise decimals (less memory) |
Boolean |
true, false |
Yes/no values |
Char |
'A' |
A single character (single quotes) |
String |
"hello" |
Text (double quotes) |
Type inference
Kotlin works out the type from the value you assign:
fun main() {
val count = 10
val price = 9.99
val initial = 'A'
val title = "Kotlin"
val ready = true
val big = 3_000_000_000
println(count::class.simpleName)
println(price::class.simpleName)
println(initial::class.simpleName)
println(title::class.simpleName)
println(ready::class.simpleName)
println(big::class.simpleName)
}
Int
Double
Char
String
Boolean
Long
3_000_000_000 is too big for an Int, so Kotlin makes it a Long
automatically. Underscores in numbers are just for readability.
Type annotations
You can write the type explicitly after a colon:
val score: Int = 100
val ratio: Double = 3.0
val id: Long = 42
Annotations are useful when you declare a variable before assigning it, or to make the intended type clear.
Types are fixed
A variable keeps its type; Kotlin never silently converts between types:
fun main() {
var level = 1
level = "two"
}
error: assignment type mismatch: actual type is 'String', but 'Int' was expected.
Common mistakes
- Writing
val ratio: Double = 3— a whole-number literal isn't automatically aDouble. Write3.0.