Type Inference and Explicit Types

Type Inference

Kotlin is statically typed: every variable has a type that is fixed at compile time. But you rarely need to write it, because the compiler infers it from the value.

Example

::class.simpleName shows the type the compiler chose.

fun main() {
    val age = 21
    val price = 99.5
    val name = "Kiran"
    val isActive = true
    val grade = 'A'
    val population = 1_400_000_000_000L

    println(age::class.simpleName)
    println(price::class.simpleName)
    println(name::class.simpleName)
    println(isActive::class.simpleName)
    println(grade::class.simpleName)
    println(population::class.simpleName)
}

Output

Int
Double
String
Boolean
Char
Long

Writing the Type Yourself

Example

Write the type after a colon when you want to be explicit, or when there is no initial value.

fun main() {
    val rating: Double = 4.5
    val city: String = "Chennai"
    var steps: Int
    steps = 8500
    println("$city $rating $steps")
}

Output

Chennai 4.5 8500

Types Cannot Change

var count = 10        // inferred as Int
count = "ten"         // ERROR: Type mismatch: inferred type is String but Int was expected

Note: This is different from JavaScript or Python. Once a variable is an Int, it stays an Int.