parse

Returns a NonNegativeInteger representing the number described by value, or throws NumberFormatException if value doesn't represent an integer, or IllegalArgumentException if value represents a negative integer.

See the Integer.Companion.parse function for the grammar of a valid integer representation.


Calling from Kotlin

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

val result: NonNegativeInteger = NonNegativeInteger.parse("+00042")
check("$result" == "42")

val invalid: Throwable? =
runCatching { NonNegativeInteger.parse("3.14") }.exceptionOrNull()
check(invalid is NumberFormatException)

val negative: Throwable? =
runCatching { NonNegativeInteger.parse("-1") }.exceptionOrNull()
check(negative is IllegalArgumentException)

check(NonNegativeInteger.parseOrNull("3.14") == null)
check(NonNegativeInteger.parseOrNull("-1") == null)

Calling from Java

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

final NonNegativeInteger result = NonNegativeInteger.parse("+00042");
final boolean check = String.valueOf(result).equals("42");
if (!check) throw new IllegalStateException("Check failed.");

try {
NonNegativeInteger.parse("3.14");
throw new IllegalStateException("Check failed.");
} catch (NumberFormatException ignored) {
}

try {
NonNegativeInteger.parse("-1");
throw new IllegalStateException("Check failed.");
} catch (IllegalArgumentException ignored) {
}

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