The toIntOrNull()
method will
parse the string as an integer number and returns it. If the string is not a valid number, then null
is returned.
fun String.toIntOrNull(): Int?
This method doesn’t take any argument.
This method returns the Int
value if the string is a valid number. Otherwise, null
is returned.
The below method demonstrates how to use the toIntOrNull()
method.
fun main() {val intNum="10"val invalidNum = "ab";val floatingNum = "10.3"println("'${intNum}'.toIntOrNull -> ${intNum.toIntOrNull()}")println("'${invalidNum}'.toIntOrNull -> ${invalidNum.toIntOrNull()}")println("'${floatingNum}'.toIntOrNull -> ${floatingNum.toIntOrNull()}")}
In the above code:
Lines 2-4: We created three string variables.
Line 6: We used the toIntOrNull
method to convert the intNum
string to an integer value. The string is a valid integer value, so it is parsed to the Int
value and returned.
Lines 7 & 8: We used the toIntOrNull
method to convert the invalidNum
and floatingNum
strings to an integer value. Both of the strings cannot be parsed to an Int
value, so null
is returned.