AdrianRaFo
09/02/2019, 8:10 AMOption.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 contextFred Friis
09/02/2019, 8:18 AMval 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
AdrianRaFo
09/02/2019, 8:19 AMAdrianRaFo
09/02/2019, 8:20 AMfoo
to None you will see the bar
and Option(bar)
respectivelyFred Friis
09/02/2019, 8:20 AMAdrianRaFo
09/02/2019, 8:25 AMImran/Malic
09/02/2019, 8:27 AMEither.catch
Imran/Malic
09/02/2019, 8:28 AMImran/Malic
09/02/2019, 8:29 AMval someString: suspend () -> Either<Throwable, String> = suspend { Either.catch { "4" } }
Fred Friis
09/02/2019, 8:33 AMprivate 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) }
}
Fred Friis
09/02/2019, 8:34 AMsimon.vergauwen
09/02/2019, 9:22 AM// but you’re saying it will execute irrespective of whether userFromCache is Some or None?It will not execute if
userFromCache
returns Some
.