Use Kotlin’s Elvis operator ?: with throw on the right-hand side:
val value: String? = getNullableValue()
val nonNullValue: String = value ?: throw IllegalArgumentException("value must not be null")
Because throw is an expression in Kotlin, it can be used after ?:.
Example
fun printLength(text: String?) {
val nonNullText = text ?: throw IllegalArgumentException("text must not be null")
println(nonNullText.length)
}
If text is not null, it is assigned to nonNullText as a non-nullable String.
If text is null, the exception is thrown.
You can also use other exception types:
val id = nullableId ?: throw IllegalStateException("ID was unexpectedly null")
A common choice is:
IllegalArgumentExceptionwhen a function argument is invalidIllegalStateExceptionwhen the object/program state is invalid
