Kotlin Type Inference — Quick Look

Anoop M Madasseri
Tech Log
Published in
2 min readJun 29, 2020

In Kotlin most of the time, you won’t need to specify the type of the objects you are working with, as long as the compiler can infer it.

So, we just need to write var or val depending on the type of variable we want to generate, and the type can normally be inferred. We can always specify a type explicitly as well. Say, for instance, you define val REQUEST_CODE = 100. Behind the scenes, REQUEST_CODE initializes with the Int datatype since the value of REQUEST_CODE is of type Int, the compiler infers that REQUEST_CODE is also a Int. Note that Kotlin is a statically-typed language. This means that the type is resolved at compile time and never changes.

Although Kotlin uses Type Inference ( automatically identify something ), which means we also have the option to specify the data type when we initialize the variable like below:

val REQUEST_CODE: Int = 100

Both act the same while converting it to byte code.

What the heck, How do Kotlin determine the data type of numbers if we use implicit declaration?

Good question, Kotlin provides a set of built-in types that represent numbers. For integer numbers, there are four types with different sizes and, hence, value ranges.

All variables initialized with integer values not exceeding the maximum value of Int have the inferred type Int. If the initial value exceeds this value, then the type is Long. To specify the Long value explicitly, append the suffix L to the value. So, whenever you strictly want to save memory it is advisable to use explicit type declaration for data types like Byte & Short.

val one = 1 // Int
val threeBillion = 3000000000 // Long
val oneLong = 1L // Long
val oneByte: Byte = 1

Reference

--

--