<@UL0QMJ80P> - `Option.getOrElse` returns the val...
# arrow
a
@Fred Friis -
Option.getOrElse
returns the value inside if the
Option
is a
Some
or return the provided param if it's a None -
Option.orElse
returns the same
Option
if it's not
None
, otherwise returns the provided
Option
The difference here is that
getOrElse
will return the value outside the
Option
context but the
orElse
keep that context
☝🏽 1
f
aah like this?
Copy code
val foo = Option.just("foo")
        
        foo.orElse { "bar" } //doesn't compile, needs an alternative Option
        foo.orElse { Option.just("bar") } //alternative Option, compiles
        
        foo.getOrElse { "bar" } //if empty default value 
        foo.getOrElse { Option.just("bar") } //not idiomatic- use orElse instead
a
yes
if you changes the
foo
to None you will see the
bar
and
Option(bar)
respectively
f
+ my understanding is none of the arrow Option methods have the dangerous problem of java 8 optional where optional.orElse() eagerly evaluates with potentially undesirable/dangerous side effects even when the optional is NOT empty, is my understanding correct?
a
never tried java 8 optionals but if an Arrow's Option is not suspended so whatever you put inside when you are creating one will be executed eagerly. The common pattern is put the nullable thing inside and continue working with the option
i
If you want a non eager Option just use the new suspended Either constructor
Either.catch
You may have to migrate to 0.10.0-Snapshot or wait for the stable release
this is how it looks like:
Copy code
val someString: suspend () -> Either<Throwable, String> = suspend { Either.catch { "4" } }
f
Copy code
private fun getUserFromCache(userId: UserId) : Option<User> {
        return cache.getUserById(userId)
    }

    private fun getUserFromDb(userId: UserId) : Option<User> {
        return db.getUserById(userId)
    }

    fun getUser(userId: UserId) : Option<User> {
        val userFromCache = getUserFromCache(userId)
        // i don't want this expensive db call to be executed if userFromCache is Some
        // as that would defeat the purpose of returning quickly from a cache
        // but you're saying it will execute irrespective of whether userFromCache is Some or None?
        return userFromCache.orElse { getUserFromDb(userId) }
    }
^^^ hope that's a clear way to articulate my problem?
s
// but you’re saying it will execute irrespective of whether userFromCache is Some or None?
It will not execute if
userFromCache
returns
Some
.
👆🏽 1
👍 1