What is Type Inference in Kotlin: Simple Explanation and Example
type inference means the compiler automatically figures out the type of a variable or expression without you having to write it explicitly. This helps keep code clean and easy to read while still being safe and clear.How It Works
Type inference in Kotlin works like a smart assistant that watches what you assign to a variable and then decides the variable's type for you. Imagine you have a box and you put an apple inside; the assistant then labels the box as "apple" without you telling it explicitly.
This means when you write val number = 5, Kotlin sees the number 5 and knows the type is Int. You don't have to write val number: Int = 5 unless you want to be very clear. This makes your code shorter and easier to write, but still safe because Kotlin checks types behind the scenes.
Type inference works for variables, function return types, and even complex expressions. It helps you focus on what your code does rather than on repetitive type details.
Example
This example shows how Kotlin infers types automatically when you declare variables.
fun main() {
val name = "Alice" // Kotlin infers String
val age = 30 // Kotlin infers Int
val height = 1.75 // Kotlin infers Double
println("Name: $name")
println("Age: $age")
println("Height: $height")
}When to Use
Use type inference whenever you want your code to be cleaner and easier to read without losing type safety. It is especially helpful when the type is obvious from the value you assign, like numbers, strings, or collections.
For example, when working with variables inside functions or small blocks of code, type inference saves time and reduces clutter. However, when the type is not clear or you want to document your code better, explicitly writing the type can help others understand your intent.
In real-world projects, type inference speeds up coding and reduces errors by letting Kotlin handle type details while you focus on logic.
Key Points
- Kotlin automatically detects variable types from assigned values.
- Type inference makes code shorter and easier to read.
- It works for variables, function returns, and expressions.
- Explicit types can still be used for clarity or documentation.
- Type inference keeps code safe by checking types at compile time.