I'm looking to do something pretty simple: I have ...
# arrow
m
I'm looking to do something pretty simple: I have a boolean expression, if it evaluates to
true
, 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:
Copy code
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?
c
I think conditionally only exists on Either, It seems like in this case it might be as concise to use a when
Copy code
when(condition) {
 true -> value().some()
 false -> None
}
Otherwise you could just wrap that in an extension like you have
m
Thanks :-)
I find repeated calls a bit nicer with the extension, not having to deal with the false branches clears up quite a bit
k
Maybe
takeIf
could be an option as well:
Copy code
value.takeIf { condition }.toOption()
m
Oh that's a nice one indeed
y
I think this is what you're looking for? https://arrow-kt.io/docs/next/apidocs/arrow-core/arrow.core/maybe.html https://github.com/arrow-kt/arrow/blob/b608a054a5318fe57d7055c35bb64a5effb053b6/ar[…]libs/core/arrow-core/src/commonMain/kotlin/arrow/core/Option.kt
Copy code
public inline fun <A> Boolean.maybe(f: () -> A): Option<A> =
  if (this) {
    Some(f())
  } else {
    None
  }
m
Indeed! That's exactly what I'm after, thanks!