- Introduction
- Editor
- Get started
- Runtime / VM
Language Guide
Design-Notes
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 thatThe 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 IntThe following table provides default types
| Type | Description |
|---|---|
| Int | Stores whole numbers from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 |
| Float | Stores fractional numbers. Sufficient for storing 15 to 16 decimal digits |
| Bool | Stores true or false values |
| String | Stores characters |
| Any | Stores 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 initializedExample
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")
}