It is also possible to cast from String to Integer or from String to Double. To do this, create a String variable and cast it by using the toInt() function. See this example:
fun main (args: Array<String>) {
var stringValue: String = "125"
var intValue = stringValue.toInt()
println("From string to int $intValue")
}
Everything is fine if the String variable contains a valid integer value, but if the String variable contains anything other than integer, Kotlin will throw a NumberCast exception. Update the following stringVariable in the previous example and verify the exception like so:
var stringValue : String = "A125"
To avoid this situation, Kotlin provides the toIntorNull function. This function will return a null if the String variable has an invalid value, such as an alpha-numeric character, whereas it will cast a string to integer if the value is numeric. It is also important to mention here that the toIntOrNull() function can return a null value, and thus the integer variable must be nullable when declared as Int?. See the following example. Create a string variable and convert it into string by using toIntOrNull function:
fun main (args: Array<String>) {
var stringValue : String = "125A"
var intValue : Int? = stringValue.toIntOrNull()
if(intValue is Int) {
println("From string to int $intValue")
}else{
println("Not a valid String")
}
}
If the string variable contains valid content, then conversion from String to Int will be successful otherwise false.