How to convert String to Int in Kotlin?

Actually, there are several ways:

Given:

// aString is the string that we want to convert to number    
// defaultValue is the backup value (integer) we'll have in case of conversion failed

var aString: String = "aString"     
var defaultValue : Int    = defaultValue

Then we have:

Operation Successful operation Unsuccessful Operation
aString.toInt() Numeric value NumberFormatException
aString.toIntOrNull() Numeric value null
aString.toIntOrNull() ?: defaultValue Numeric value defaultValue

If aString is a valid integer, then we will get is numeric value, else, based on the function used, see a result in column Unsuccessful Operation.


As suggested above, use toIntOrNull().

Parses the string as an [Int] number and returns the result or null if the string is not a valid representation of a number.

val a = "11".toIntOrNull()   // 11
val b = "-11".toIntOrNull()  // -11
val c = "11.7".toIntOrNull() // null
val d = "11.0".toIntOrNull() // null
val e = "abc".toIntOrNull()  // null
val f = null?.toIntOrNull()  // null

val i = "42".toIntOrNull()

Keep in mind that the result is nullable as the name suggests.


You could call toInt() on your String instances:

fun main(args: Array<String>) {
    for (str in args) {
        try {
            val parsedInt = str.toInt()
            println("The parsed int is $parsedInt")
        } catch (nfe: NumberFormatException) {
            // not a valid int
        }
    }
}

Or toIntOrNull() as an alternative:

for (str in args) {
    val parsedInt = str.toIntOrNull()
    if (parsedInt != null) {
        println("The parsed int is $parsedInt")
    } else {
        // not a valid int
    }
}

If you don't care about the invalid values, then you could combine toIntOrNull() with the safe call operator and a scope function, for example:

for (str in args) {
    str.toIntOrNull()?.let {
        println("The parsed int is $it")
    }
}

Tags:

Kotlin