This article was translated from Japanese by Claude Code.
The Kotlin code in this article was verified with kotlin-stdlib-common 1.3.72.
I found this and thought it was convenient so here’s a note 📝.
In Java, when a value expected to be non-null is actually null, you write code like this to throw an exception:
if (nonNullIsExpceted == null) {
throw new IllegalStateException("nonNullIsExpceted should not be null.");
}In Kotlin, you can write similar code like this:
Pattern 1: Using throw#
if (nonNullIsExpceted == null) {
throw IllegalStateException("nonNullIsExpceted should not be null.")
}
val valid = nonNullIsExpected ?: throw IllegalStateException("nonNullIsExpceted should not be null.")Pattern 2: Using error function#
if (nonNullIsExpceted == null) {
error("nonNullIsExpceted should not be null.")
}
val valid = nonNullIsExpected ?: error("nonNullIsExpceted should not be null.")Both patterns in Kotlin have the same meaning. The error function is implemented like this:
/**
* Throws an [IllegalStateException] with the given [message].
*
* @sample samples.misc.Preconditions.failWithError
*/
@kotlin.internal.InlineOnly
public inline fun error(message: Any): Nothing = throw IllegalStateException(message.toString())I thought it was concise and intuitive to write. Also, the fact that the message parameter is non-null and requires some error message in the API specification is nice too.