Learn
Data Types & Variables
Type Inference

In Kotlin, we can save keystrokes and optimize our variable declarations with a feature known as type inference.

Type inference indicates that the compiler can infer the type of a declared variable, and its data type can be omitted in the declaration. Take a look at the following variable declaration:

var lightsOn: Boolean = true

We’re explicitly stating the type of variable, but the Kotlin compiler is also intelligent enough to make this assumption even with the absence of a type:

var lightsOn = true // valid declaration

The compiler recognizes that a true or false value stored in a variable falls under the Boolean data type, thus the lightsOn variable is a Boolean.

It’s important to know that regardless of how a variable is declared, its type cannot change throughout a program. A Boolean variable, whether explicitly stated or inferred, can only hold a true or false value.

If we try to assign a value that’s not a Boolean:

lightsOn = "no" // error

The compiler will throw the following error:

Inference.kt:4:14: error: type mismatch: inferred type is String but Boolean was expected
  lightsOn = "no" 

Note: Variable declarations with explicitly specified data types and those with inferred data types are both valid ways in creating variables. Each syntax will be accepted by the compiler, thus choosing one or the other is simply up to the developer’s preference.

Instructions

1.

In Inference.kt, we’ve added a print() statement with some Kotlin code within the main() function that outputs the inferred data type for a variable, called typeTest. Don’t worry about understanding exactly how this code works now, we’ll cover what these symbols and names mean later in the course. For now, we’ll just use it to show the type of data that was inferred by the compiler.

Above the print() statement, declare typeTest and initialize it with any value from this list:

  • "6"
  • 6
  • true
  • "false"
  • 2.6

Observe the inferred type in the terminal. Was it what you expected?

Assign and test a few other values for typeTest.

Folder Icon

Take this course for free

Already have an account?