Kotlin How to Convert String to Int Easily
In Kotlin, you can convert a string to an integer using
toInt() like this: val number = "123".toInt().Examples
Input"123"
Output123
Input"0"
Output0
Input"-45"
Output-45
How to Think About It
To convert a string to an integer in Kotlin, think of the string as a number written in text form. You use the
toInt() function to tell Kotlin to read that text and turn it into a number you can use for math or other operations.Algorithm
1
Get the input string that represents a number.2
Use the <code>toInt()</code> function on the string to convert it to an integer.3
Store or use the resulting integer value.Code
kotlin
fun main() {
val strNumber = "123"
val number = strNumber.toInt()
println(number)
}Output
123
Dry Run
Let's trace converting the string "123" to an integer.
1
Start with string
strNumber = "123"
2
Convert string to int
number = strNumber.toInt() // number = 123
3
Print the integer
Output: 123
| Step | Value |
|---|---|
| strNumber | "123" |
| number | 123 |
Why This Works
Step 1: Using toInt()
The toInt() function reads the string characters and converts them into an integer number.
Step 2: Valid string format
The string must contain only digits (and optionally a leading minus sign) to convert successfully.
Step 3: Result is an integer
After conversion, you get a real number type Int that you can use in calculations.
Alternative Approaches
toIntOrNull()
kotlin
fun main() {
val strNumber = "abc"
val number = strNumber.toIntOrNull()
println(number) // prints null
}This method returns null instead of throwing an error if the string is not a valid number.
Integer.parseInt()
kotlin
fun main() {
val strNumber = "456"
val number = Integer.parseInt(strNumber)
println(number)
}This is a Java method available in Kotlin but less idiomatic than <code>toInt()</code>.
Complexity: O(n) time, O(1) space
Time Complexity
The toInt() function reads each character once, so it takes time proportional to the string length.
Space Complexity
Conversion uses a fixed amount of extra space, so it is constant space.
Which Approach is Fastest?
toInt() and Integer.parseInt() have similar speed; toIntOrNull() adds safety but with minimal overhead.
| Approach | Time | Space | Best For |
|---|---|---|---|
| toInt() | O(n) | O(1) | Simple, valid strings |
| toIntOrNull() | O(n) | O(1) | Safe conversion with error handling |
| Integer.parseInt() | O(n) | O(1) | Java interoperability |
Use
toIntOrNull() to safely convert strings that might not be numbers.Trying to convert a non-numeric string with
toInt() causes a crash.