Kotlin Tip #3: Utilize Type Inference — 100 Kotlin Tips in 100 Days
Twitter | LinkedIn | YouTube | Instagram
Tip #2: Leverage String Templates
In Kotlin, you don’t need to explicitly declare the type of a variable if it can be inferred from the initializer expression:
val name = "John Doe" // The compiler infers the type String
var age = 30 // The compiler infers the type Int
It also works with objects:
data class Person(val name: String, val age: Int)
val person = Person(name, age)
It can be used to infer the return type of a function:
fun square(number: Int) = number * number
// The compiler infers the return type Int
In lamba expressions:
val numbers = listOf(1, 2, 3)
val doubled = numbers.map { it * 2 }
// The compiler infers the lambda parameter type and return type
And generics:
fun <T> listOf(vararg items: T): List<T> {
return items.toList()
}
val numbers = listOf(1, 2, 3) // The compiler infers listOf<Int>
By intelligently inferring types, developers are allowed to focus more on expressing their intentions and less on boilerplate-type declarations, making the overall development experience more enjoyable and productive.
Type inference isn’t a Kotlin exclusive, though. The var keyword was introduced in Java 10 in 2018 but hasn’t been widely adopted. In Kotlin, in contrast, type inference is embraced as a core feature and aligns with the philosophy of conciseness and clarity without compromising safety.
I hope you have enjoyed the third tip of our series! Don’t forget to subscribe and stay tuned for more Kotlin tips!
Stay curious!
Contribute
Writing takes time and effort. I love writing and sharing knowledge, but I also have bills to pay. If you like my work, please, consider donating through Buy Me a Coffee: https://www.buymeacoffee.com/RaphaelDeLio
Or by sending me BitCoin: 1HjG7pmghg3Z8RATH4aiUWr156BGafJ6Zw
Follow Me on Social Media
Stay connected and dive deeper into the world of Kotlin with me! Follow my journey across all major social platforms for exclusive content, tips, and discussions.