Variables in kotlin

Reading Time: 2 minutes

In many programming languages you start the variable declaration with a type. In Kotlin typedeclaration like this wouldn’t work, because it lets you omit the types form many variable declarations. Thus in Kotlin you start with a keyword, and you may (or may not) put the type after the variable name. Let’s declare two variables

This example omit the type declarations, but you can also specify the type explicitly if you want to:

Just as with expression-body functions, if you don’t specify the type, the complier analyzes the initializer expression and uses its type as the variable type. In this case, the initializer, 42, has Int type, so the variable will have the same type.

If you use a floating-point constant, the variable will have the type Double.

 8.3 * 106 = 8300000.0

If a variable doesn’t have an initializer, you need to specify its type explicitly

The compiler can’t infer the type if you give no information about the values that can be assigned to this variable.

Mutable and inmutable variables

There are two types of variables to declare your variables

  • val (from value
    • Immutable reference.
    • A variable declared with val can’t be reassigned after it’s initialized.
  • var (from variable)
    • Mutable reference. 
    • The value of such a variable can be changed.
By default, you should strive to declare all variables in Kotlin with the val keyword. Change it to var only if necessery. Using immutable references, immutable objects, and functions without side effects makes your code closer to the functional style.

If the compiler can be sure that the initialization statement execute only once, then you can initialize it with different values.
See example below

 // Yes, can be executed

The val reference is inmutable, but if the object what is it points, can be mutable.

As we talked about the value of the var reference can be changed, but its type is fixed.

 Source: Dimitry Jemerov, Svetlana Isakova: Kotlin in action 



Follow and like us:
Click to rate this post!
[Total: 0 Average: 0]

Leave a comment

stay informed!

Subscribe to receive exclusive content and notifications