Task
In this challenge, you needed to declare an immutable variable of type Int
and initially assign it a value of 100. You then needed to print myFirstVariable
.
Solution
Let’s look at each component separately:
-
Immutable Variable - When declaring a variable, we first need to specify if it is immutable or mutable. An immutable variable is declared using the
val
keyword. -
Variable Name - After specifying the type of variable, we need to give the variable a name. In our case, the name of the variable is
myFirstVariable
. -
Data Type - After giving the variable an identifier, we need to specify its data type which is done using
:
. In our case, we needed a variable of typeInt
hence, we would need to write:Int
. -
Assigning a Value - For assigning an initial value to the variable, we insert a
=
after the data type, followed by the desired value to be assigned. In our case, that value was 100.
val myFirstVariable: Int = 100
- Finally, use either the
print
orprintln
method to printmyFirstVariable
.
print(myFirstVariable)
or
println(myFirstVariable)
You can find the complete solution below:
val myFirstVariable: Int = 100print(myFirstVariable)
In the next lesson, we will learn about type casting.