How to use the toIntOrNull() method of String in Kotlin
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.
Syntax
fun String.toIntOrNull(): Int?
Parameter
This method doesn’t take any argument.
Return value
This method returns the Int value if the string is a valid number. Otherwise, null is returned.
Code
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()}")}
Explanation
In the above code:
-
Lines 2-4: We created three string variables.
-
Line 6: We used the
toIntOrNullmethod to convert theintNumstring to an integer value. The string is a valid integer value, so it is parsed to theIntvalue and returned. -
Lines 7 & 8: We used the
toIntOrNullmethod to convert theinvalidNumandfloatingNumstrings to an integer value. Both of the strings cannot be parsed to anIntvalue, sonullis returned.