Variable in Kotlin language

Photo by Jess Bailey on Unsplash

Variable in Kotlin language

Variable

Variable, in general, is like the variable in mathematics you define it and store a value to use this value later in an equation, for example.

In programming there's no difference, for a simple illustration, you can think of a variable as a box, and you use this box to store something. And there are multiple boxes in your warehouse so how you can distinguish between them? You can give each one a name right. So from here, we can understand that a variable has a name and a value that we store in it. Furthermore, there's an important thing you should know each variable must have a type, it's the type of data that is stored in it. So until now, we that each variable has a name, value, and a type.

In Kotlin language, the default syntax for defining a variable is

var/val variable-name : datatype = value

And the above syntax call declaring and assigning value to a variable, we declared a variable named 'name' and assigned it a value of Kotlin. Some programming languages let you declare a variable without assigning it a value.

For example, In Kotlin

var name: String ="Kotlin"

Var and val are reserved words in the Kotlin language, 'name' is the name of our variable, and string is the data type that we want to store in the variable. And it means that we would like to store a string. There were other data types, and we'll discuss them later. Kotlin, it's the value of the variable, and it was put in the quotation mark to denote to the compiler it's a string.

What's the difference between var and val

Its simple var means that we can change the value of the variable in runtime which means its a mutable. In the above example, we change the name value to:

name = "Java"

name = "Swift"

There are folks who say it's an acronym for variable and it means we can change it. But the val we can't change its value which means it is immutable(cannnot be changed) if we write:

//Declaring a val variable
val name :String = "Kotlin"

//Trying to change the value of the name 
name = "Java"

It'll give you an error saying that you cannot change the value of a val variable, you should change it to the var.

There's the last thing, We can declare a variable and assigned it a value without specifying a type like below

val age = 20

And the Kotlin compiler can know the type by itself because the language has a concept called type inference. I think we should talk about it in a separate post. Note that in the above example, we define a variable that holds an integer value.

Did you find this article valuable?

Support Khalid Mohammed by becoming a sponsor. Any amount is appreciated!