Type inference
- Kotlin course
- Beginner
- Lesson 8/116
- 4 min
Learn type inference and explicit type declarations.
Type inference
Kotlin is statically typed; every variable has a type known at compile time. But you usually don't need to write the type explicitly. The compiler infers it from the assigned value.
For example, when you write val n = 5, Kotlin infers n is Int. To state the type explicitly, write val n: Int = 5. Both forms are valid.
val n = 5 // Int is inferred
val pi: Double = 3.14 // type written explicitlyPractice Write the type explicitly
Write a fun main(). Declare val pi: Double = 3.14 and print with println(pi).
Sample solution
fun main() {
val pi: Double = 3.14
println(pi)
}Expected output
3.14
When to write the type explicitly?
Type inference is enough most of the time; sometimes writing the type explicitly is more readable. Examples include a function's return type, a class property, or cases where the expected type is unclear.
Also, writing val x: Double = 5 makes Kotlin convert 5 from Int to Double, so x becomes 5.0. Adding the type makes the code's intent explicit.
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Write the type
val pi: ____ = 3.14
val pi: Double = 3.14
Explanation: Decimal numbers are of type Double.
2 What is the type of name in `val name = "Alex"`?
- Int
- Boolean
- Char
- String Correct answer
Explanation: A value in double quotes is a String.
3 Type inference: match the terms
| Term | Meaning |
|---|---|
5 |
Int |
3.14 |
Double |
true |
Boolean |
'A' |
Char |