Kotlin’s powerful type inference reduces the syntax clutter inherent to Java and brings us closer to a dynamically-typed language like Python. This is already visible when declaring and initializing variables.
Consider this Java code:
Note how we’ve essentially told Java the type (
int) of the variable twice:
once in the declaration (
int i) and a second time through the initialization
Shouldn’t the compiler be able to help us here?
To be fair, since Java 10 the following has been valid Java code:
So even the Java compiler can now infer variable types.
And, in what may or may not be a coincidence, the
var modifier in Java does
have the same meaning in Kotlin.
Variable initialization is extremely simple in Python:
i = 5
Of course, this is facilitated by the fact that Python is dynamically typed, and doesn’t do compile-time type checking. (Or compilation, really.)
However, it’s worth considering whether this is really a good design choice or an anti-pattern—because it makes it impossible to distinguish initialization from assignment.
For example, consider the code snippet above again:
i = 5 // Am I modifying an existing variable or declaring a new one?
It’s impossible to tell.
In the common case where we combine declaration and initialization, Kotlin is quite capable of inferring the type of variables:
Kotlin can usually accomplish this regardless of what is on the right side of the assignment. For example, that could be a function call:
However, the example above demonstrates both that Kotlin won’t always infer types for you—even when it could—and shows us our first examples of typing in Kotlin.
All data in Kotlin is represented using the same 8 primitive types available in Java:
The example above also shows us the syntax for specifying a type when we declare a variable. If we declare but don’t initialize a variable we need to specify the type explicitly. (Since otherwise, how would Kotlin know?)
Unlike Java, all of Kotlin’s basic types are objects:
Instead, it’s probably more appropriate to describe Kotlin’s basic types as akin to Java’s boxing types: