is there a shorthand to access an optional throwin...
# announcements
i
is there a shorthand to access an optional throwing an exception if it's not set?
t
orElseThrow
?
r
You mean something like this but shorter?
Copy code
myOptional ?: throw Error("myOptional")
i
don't see it in autocompletions 🤔
yeah but I'd like to chain it. I tried writing this:
Copy code
fun <T> T?.unwrap(errorMsg: String): T =
    this ?: error(errorMsg)
But it doesn't get rid of the optional when chaining:
Copy code
inputs.cough?.unwrap("Cough not set").type = type // error after ), because it's missing ?
so all I can do now is
Copy code
(inputs.cough ?: error("Cough not set")).type = type
which is probably not so bad
t
Ah its a nullable not the type Optional 🤓
requireNotNull
already exists in kotlin
r
@iex I see. You can sort of do this using experimental feature: contracts. Given:
Copy code
@ExperimentalContracts
fun <T> T.unwrap(errorMessage: String): T {
    contract {
        returns()
    }
    return this ?: throw Error(errorMessage)
}
Usage:
Copy code
val a: String?
a = null
a?.unwrap("a is Null!!")
a // a would smart cast to not-null here.
It's used by
requireNotNull
,
checkNotNull
@thana recommended.
t
btw the way the shortest shortcut is
!!
if you don't care for the concrete error 🙈
😂 1
r
The ultimate shortcut
😂 1
i
oh that with contracts is interesting
aware of
!!
😉 I wanted an error message
thanks!