parseOrNull

fun parseOrNull(value: String): Integer?

Returns an Integer representing the number described by value, or returns null if the value doesn't represent an integer.

A valid integer representation is defined as:

integer = [sign] digit {digit}
sign = "+" | "-"
digit = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9"

(grammar written in Wirth-style EBNF, where [] denotes optionality and {} denotes repetition)

Leading zeros and plus sign are ignored when interpreting value. As a result, calling this function with 123 and +000123 produces the same integer.


Calling from Kotlin

Here's an example of calling this function from Kotlin code:

fun parsesTo(input: String, expected: String) {
check(Integer.parse(input).toString() == expected)
check(Integer.parseOrNull(input).toString() == expected)
}

fun parsingFailsWith(input: String) {
val exception: Throwable? = runCatching { Integer.parse(input) }
.exceptionOrNull()
check(exception is NumberFormatException)

check(Integer.parseOrNull(input) == null)
}

// Parsing normalizes zero:
parsesTo(input = "0", expected = "0")
parsesTo(input = "+0", expected = "0")
parsesTo(input = "-0", expected = "0")
parsesTo(input = "000", expected = "0")
parsesTo(input = "+000", expected = "0")
parsesTo(input = "-000", expected = "0")

// Parsing removes leading plus sign:
parsesTo(input = "+42", expected = "42")

// Parsing removes leading zeros:
parsesTo(input = "00042", expected = "42")
parsesTo(input = "-00042", expected = "-42")

// Parsing preserves canonical representation:
parsesTo(input = "42", expected = "42")
parsesTo(input = "-42", expected = "-42")

// Parsing fails with noninteger string:
parsingFailsWith("")
parsingFailsWith("+")
parsingFailsWith("-")
parsingFailsWith("12a")
parsingFailsWith("3.14")
parsingFailsWith(" 42")

This function is hidden from Java, because nullability is not explicit in its type system.

See the parse function for throwing an exception instead of returning null in case of invalid value.

Since

5.2.0