Variables

Variables are containers for storing data values

To create a variable, use val or var, and assign a value to it with the equal sign (=)

Syntax

val variableName = value var variableName = value val variableName //Wrong because compiler can't infer the type and the value is not initialized val variableName = 1 variableName = 2 //Wrong because variableName was declarated as val, only var can do that

The difference between val and var is that var is mutable but val is immutable

The compiler will infer the type from the assigned value, so you can write without declaration, but if you want explicit you can declare type

Variable with type

val variableName: type = value var variableName: type = value var variableName: Int = "Hi there!!" //Wrong because compiler infer String but type of variableName is Int

The following table provides default types

TypeDescription
IntStores whole numbers from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
FloatStores fractional numbers. Sufficient for storing 15 to 16 decimal digits
BoolStores true or false values
StringStores characters
AnyStores any objects (testing)

Sometimes, you must use nullable value, we provides a sugar syntax to work with these.

Sugar syntax

val variableName: type? //Default null var variableName: type? //Default null val variableName? = value //Compiler inference and marks nullable var variableName? = value //Compiler inference and marks nullable val variableName! = value //Compiler inference and marks non nullable var variableName! = value //Compiler inference and marks non nullable val variableName!=value //Wrong because compiler is confused between operator != and non nullable val variableName! //Wrong because compiler can't infer the type and the value is not initialized val variableName? //Wrong because compiler can't infer the type and the value is not initialized

Example

val name = "John" //String val age = 18 //Int val money: Float = 4.5 //Float val email! = "autolang@gmail.com" val child: Int? //Null value println("Hello everyone, my name is " + name + " and I'm " + age) println("Hello everyone, my name is ${name} and I'm ${age}") println("Now I have $money dollar and my email is $email") if (child == null) { println("I don't have any childs") } else { println("I have some childs") }