Menu
Coddy logo textTech

Type Inference

Part of the Fundamentals section of Coddy's Kotlin journey. Lesson 6 of 93.

Kotlin can automatically figure out the type of a value. This is called type inference:

fun main() {
    val name = "Alice"   // Kotlin infers this is a String
    val age = 25         // Kotlin infers this is an Int
    val price = 9.99     // Kotlin infers this is a Double
}

But you can also explicitly declare the type using a type annotation. You write a colon after the name, followed by the type:

fun main() {
    val name: String = "Alice"
    val age: Int = 25
    val price: Double = 9.99
    val isActive: Boolean = true
}

Type annotations are useful when:

  • You want to be extra clear about what type a value is
  • You declare a variable without an initial value
fun main() {
    var score: Int   // Declared but not yet assigned
    score = 100      // Assigned later
}

Without the type annotation, Kotlin wouldn't know what type score should be.

challenge icon

Challenge

Beginner

Create four val declarations without explicit type annotations: city holding "Oslo", platform holding 4, fare holding 12.5, and isExpress holding false. Let Kotlin infer their types. Print their values on four separate lines in that order.

Try it yourself

fun main() {
    // Declare the four values without type annotations.
    // Print them in the requested order.
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals

Practice on your own: Kotlin playground