toIntOrNull

Parses the string to an Int number or returns null if the string is not a valid representation of an Int.

The string must consist of an optional leading + or - sign and decimal digits (0-9), and fit the valid Int value range (within Int.MIN_VALUE..Int.MAX_VALUE), otherwise null is returned.

Since Kotlin

1.1

Samples

import kotlin.test.assertFailsWith

fun main() { 
   //sampleStart 
   println("0".toIntOrNull()) // 0
println("42".toIntOrNull()) // 42
println("042".toIntOrNull()) // 42
println("-42".toIntOrNull()) // -42
// Int.MAX_VALUE
println("2147483647".toIntOrNull()) // 2147483647
// Int overflow
println("2147483648".toIntOrNull()) // null
// 'a' is not a digit
println("-1a".toIntOrNull()) // null
// underscore
println("1_00".toIntOrNull()) // null
// whitespaces
println(" 22 ".toIntOrNull()) // null 
   //sampleEnd
}

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

Since Kotlin

1.1

Throws

when radix is not a valid radix for string to number conversion.