How to convert String to Int in Kotlin?

How to convert String to Int in Kotlin?

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 dont 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)
    }
}

Actually, there are several ways:

Given:

var numberString : String = numberString 
// number is the int value of numberString (if any)
var defaultValue : Int    = defaultValue

Then we have:

Operation Numeric value Non-numeric value
numberString.toInt() number NumberFormatException
numberString.toIntOrNull() number null
numberString.toIntOrNull() ?: defaultValue number defaultValue

If numberString is a valid integer, we get number, else see a result in column Non-numeric value.

How to convert String to Int in Kotlin?

val i = 42.toIntOrNull()

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

Leave a Reply

Your email address will not be published. Required fields are marked *