ensureNotNull
Ensures that the value is not null; otherwise, Raise.raises a logical failure of type Error.
In summary, this is a type-safe alternative to requireNotNull, using the Raise API.
Example
@JvmInline
value class FullName(val name: String)
sealed interface NameError {
object NullValue : NameError
}
context(Raise<NameError>)
fun fullName(name: String?): FullName {
val nonNullName = ensureNotNull(name) { NameError.NullValue }
return FullName(nonNullName)
}
fun main() {
recover({
fullName("John Doe") // valid
fullName(null) // raises NameError.NullValue error
}) { error ->
// Handle errors in a type-safe manner
when (error) {
NameError.NullValue -> {}
}
}
}
Content copied to clipboard