Kotlin value assignment and type inference

Categories:
4 minute read
In this article, we will explain some of the finer points you need to know about defining variables in the Kotlin programming language. We have prepared this article in addition to the rules we explained in our previous two articles ("Kotlin Variable and Value definition", “Constants and variables in Kotlin”).
We all know that numbers and letters are different types. While mathematical operations can be performed with numbers, mathematical operations cannot be performed with texts. We should note that this distinction also exists in programming languages. Therefore, every variable must have a type.
The variable definition template in the Kotlin programming language is as follows.
At the very beginning is the expression val or var. Val or var selection is made depending on the behavior of the value of the variable. We explained the differences in our article titled “Kotlin Variable and Value Definition”.
identifier: So it should be the name of the variable. Choosing a name that is meaningful and explains what it does to avoid confusion with other variables will always be beneficial.
Type: We write the type of the variable here. Expressions that express the type of the value, such as String, Int, Boolean, start with a capital letter. Type is written after writing a colon after the name of the variable.
Initialization: We assign the initial value to our variable. It means initial value. When the type of the variable is determined, the initial value does not have to be assigned immediately. We will give examples of correct and incorrect usage below.
Now let’s write an example according to this template. The example below has a structure that fulfills all the rules completely.
As seen in the example, the variable name and type are determined, but the initial value is determined elsewhere. This usage is correct. If the initial value is determined at another time, it is necessary to write the variable type.
Incorrect variable definition
Defining a variable without both a data type and an initial value will cause you to encounter an error. The usage below is incorrect. Your program will not compile.