Lesson 6 Programming in Kotlin
![Kotlin-logo.png]()
Lesson 6 Programming in Kotlin
Conversion between variable types
We will explain the idea through an example:
fun main (args: Array <String>)
{
var x: String = "12345"
var y: Int?
y = x.toInt ()
print (y)
}
In this example we defined the variable x of the string text type, we assigned the value 1234 as text, and we defined the y variable of the numeric type
To store the value of the variable x in variable y, the type must be converted so we wrote the command:
y = x.toInt ()
Which converted the text x value to a numeric value and then stored the result in the y variable
That is, you must convert between variable types when we want to store one value in another
But we must be careful during the conversion process so as not to lose information
For example, if we have a variable of 12.99 = x of type double and variable y of int type, when converting from double to int we will lose the decimal section
y = x.toInt ()
The result will be y = 12 because int type stores only integers not the decimal