Marc Plano-Lesay
11/18/2022, 11:04 PMtrue
, I want to evaluate something and return it as a Some
, otherwise I want to return a None
. Here's a pretty trivial implementation that might be clearer:
fun <A> Option.Companion.cond(condition: Boolean, value: () -> A): Option<A> = if (condition) {
value().some()
} else {
None
}
Is there anything built-in that I'm missing?Cody Mikol
11/19/2022, 12:16 AMwhen(condition) {
true -> value().some()
false -> None
}
Otherwise you could just wrap that in an extension like you haveMarc Plano-Lesay
11/19/2022, 12:17 AMMarc Plano-Lesay
11/19/2022, 12:17 AMkartoffelsup
11/19/2022, 6:59 AMtakeIf
could be an option as well:
value.takeIf { condition }.toOption()
Marc Plano-Lesay
11/19/2022, 7:04 AMYeogai C
11/19/2022, 10:43 PMpublic inline fun <A> Boolean.maybe(f: () -> A): Option<A> =
if (this) {
Some(f())
} else {
None
}
Marc Plano-Lesay
11/19/2022, 10:43 PM