Variables are like containers for storing data/values.
We have two keywords to create variables, var and val and to assign the value to it we use ( = ).
var variableName = value; val variableName2 = value2;
Just like, let’s say we want to store some values in variables.
var username = "John Doe" var age = 34 println(username) // will print username println(age) // will print age
Val vs Var:
- Val: The value stored in a variable created with val keyword is immutable (not changeable)
- Var: The value stored in a variable created with var keyword is mutable (changeable)
In Kotlin, the variable can either be declared with type or without type. If it’s declared without type, its type will be specified automatically by Kotlin.
If you want to create a variable that should store text, or number. Look at the example below.
var username = "John Doe" // String (text) var age = 34 // Int (number) println(username) // will print text username println(age) // will print number age
if we specify the appropriate type this will result the same.
var username : String username = "John Doe" println(username) // will print text username
You will learn about Data Types in the next chapter.