Type inference

Declaring types in Kotlin is optional. This is a feature of a Kotlin compiler called Type inference. The compiler can infer the type from the context of the usage. Kotlin is a strongly and statically typed language, so omitting types doesn’t mean that you lose type safety. 

Here’s an example of type inference:

val str = "Kotlin"

str variable is of type String and the compiler knows this from the String literal that is initializing the variable. That’s why, if you try to assign a different type to this variable, you'll get a compiler error, as can be seen in the following:

var str = "Kotlin"
str = 1 // compiler error

Type inference doesn’t just work on local variables, but also on functions with expression bodies, generic types, closures and lambdas. You’ll see more type inference in practice in following chapters.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.135.191.47