0
0
Kotlinprogramming~5 mins

Type inference by the compiler in Kotlin

Choose your learning style9 modes available
Introduction
Type inference helps the compiler guess the type of a value so you don't have to write it every time. This makes your code shorter and easier to read.
When you want to declare a variable without writing its type explicitly.
When you assign a value to a variable and want the compiler to figure out its type.
When you want cleaner code without losing type safety.
When working with functions that return values and you want the compiler to know the return type.
When you want to avoid clutter in your code but still keep it safe.
Syntax
Kotlin
val variableName = value
var variableName = value
The compiler looks at the value on the right side and decides the type automatically.
Use val for read-only variables and var for variables that can change.
Examples
The compiler knows number is an Int because 10 is an integer.
Kotlin
val number = 10
The compiler infers name is a String from the text in quotes.
Kotlin
val name = "Alice"
Here, price is a Double because 9.99 is a decimal number.
Kotlin
var price = 9.99
The compiler infers isActive is a Boolean from the value true.
Kotlin
val isActive = true
Sample Program
This program shows variables declared without explicit types. The compiler figures out the types from the assigned values.
Kotlin
fun main() {
    val age = 25
    val greeting = "Hello, Kotlin!"
    var temperature = 36.6
    val isSunny = false

    println("Age: $age")
    println("Greeting: $greeting")
    println("Temperature: $temperature")
    println("Is it sunny? $isSunny")
}
OutputSuccess
Important Notes
Type inference does not mean the compiler guesses randomly; it uses the value's type to decide.
If you want, you can still write the type explicitly for clarity, like val age: Int = 25.
Type inference works well with simple assignments but sometimes you need to specify types for complex cases.
Summary
Type inference lets the compiler find out variable types automatically.
It makes code shorter and easier to read without losing safety.
Use it when you assign values directly to variables.