This article explores different ways to convert a string to an integer in Kotlin. If the value of the specified string is negative, the sign should be preserved in the resultant integer.

1. Using toInt() function

You can easily convert the given string to an integer with the toInt() function. It throws a NumberFormatException if the string does not contain a valid integer.

Download Code

Output:

The value is 1024

 
Note that this function fails when the numeric value falls outside the valid integer data type range. If you need to work with the larger values, consider using the toLong() function.

2. Using toIntOrNull() function

Alternatively, you can use the toIntOrNull() function, which parses the string as an Int number and returns the result or null if the string is not a valid representation of a number.

Download Code

Output:

The value is 1024

 
You can also combine toIntOrNull() with the safe call operator and a scope function.

Download Code

Output:

The value is 1024

 
As with the toInt() function, this fails when the numeric value falls outside the integer range. If you need to work with the larger values, consider using the toLongOrNull() function.

3. Using valueOf() function

The Integer class has valueOf() function that returns the integer value specified by the string.

Download Code

That’s all about converting a string to an integer in Kotlin.