parse
Returns a NonPositiveInteger representing the number described by value, or throws NumberFormatException if value doesn't represent an integer, or IllegalArgumentException if value represents a positive 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: NonPositiveInteger = NonPositiveInteger.parse("-00042")
check(result.toInteger() == Integer.fromLong(-42))
val invalid: Throwable? =
runCatching { NonPositiveInteger.parse("3.14") }.exceptionOrNull()
check(invalid is NumberFormatException)
val positive: Throwable? =
runCatching { NonPositiveInteger.parse("1") }.exceptionOrNull()
check(positive is IllegalArgumentException)
check(NonPositiveInteger.parseOrNull("3.14") == null)
check(NonPositiveInteger.parseOrNull("1") == null)Content copied to clipboard
Calling from Java
Here's an example of calling this function from Java code:
final NonPositiveInteger result = NonPositiveInteger.parse("-00042");
final boolean check = result.toInteger().equals(Integer.fromLong(-42));
if (!check) throw new IllegalStateException("Check failed.");
try {
NonPositiveInteger.parse("3.14");
throw new IllegalStateException("Check failed.");
} catch (NumberFormatException ignored) {
}
try {
NonPositiveInteger.parse("1");
throw new IllegalStateException("Check failed.");
} catch (IllegalArgumentException ignored) {
}Content copied to clipboard
See the parseOrNull function for returning null instead of throwing an exception in case of invalid or positive value.