parse
Returns a NonZeroInteger representing the number described by value, or throws NumberFormatException if value doesn't represent an integer, or IllegalArgumentException if value represents zero.
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: NonZeroInteger = NonZeroInteger.parse("+00042")
check("$result" == "42")
val invalid: Throwable? =
runCatching { NonZeroInteger.parse("3.14") }.exceptionOrNull()
check(invalid is NumberFormatException)
val zero: Throwable? =
runCatching { NonZeroInteger.parse("0") }.exceptionOrNull()
check(zero is IllegalArgumentException)
check(NonZeroInteger.parseOrNull("3.14") == null)
check(NonZeroInteger.parseOrNull("0") == null)Content copied to clipboard
Calling from Java
Here's an example of calling this function from Java code:
final NonZeroInteger result = NonZeroInteger.parse("+00042");
final boolean check = String.valueOf(result).equals("42");
if (!check) throw new IllegalStateException("Check failed.");
try {
NonZeroInteger.parse("3.14");
throw new IllegalStateException("Check failed.");
} catch (NumberFormatException ignored) {
}
try {
NonZeroInteger.parse("0");
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 zero value.