Basic types
Every variable and data structure in Kotlin has a type. Types are important because they tell the compiler what you are allowed to do with that variable or data structure. In other words, what functions and properties it has.
In the last chapter, Kotlin was able to tell in the previous example that customers has type Int. Kotlin's ability to infer the type is called type inference. customers is assigned an integer value. From this, Kotlin infers that customers has a numerical type Int. As a result, the compiler knows that you can perform arithmetic operations with customers:
In total, Kotlin has the following basic types:
Category | Basic types | Example code |
|---|---|---|
|
| |
|
| |
|
| |
|
| |
|
| |
|
|
For more information on basic types and their properties, see Types overview.
With this knowledge, you can declare variables and initialize them later. Kotlin can manage this as long as variables are initialized before the first read.
To declare a variable without initializing it, specify its type with :. For example:
If you don't initialize a variable before it is read, you see an error:
Now that you know how to declare basic types, it's time to learn about collections.
Practice
- Declare explicit types for variables
Explicitly declare the correct type for each variable:
fun main() { val a: Int = 1000 val b = "log message" val c = 3.14 val d = 100_000_000_000_000 val e = false val f = '\n' }fun main() { val a: Int = 1000 val b: String = "log message" val c: Double = 3.14 val d: Long = 100_000_000_000_000 val e: Boolean = false val f: Char = '\n' }