Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

tointornull
kotlin
string

How to use the toIntOrNull() method of String in Kotlin

Programming Bytes

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()}")

}
Using toIntOrNull method

Explanation

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.

RELATED TAGS

tointornull
kotlin
string
RELATED COURSES

View all Courses

Keep Exploring