https://kotlinlang.org logo
Title
b

Ben Madore

09/20/2019, 2:45 PM
so can call it like:
fun getFoo(): Foo? {
// lookup logic for foo
  return foo?. someName { nullFunc = { <http://log.info|log.info>{"didn't find it"} }, nonNullFunc = { <http://log.info|log.info>{"Found $this"}} }
}
a

Adam Powell

09/20/2019, 2:50 PM
seems like that would make things more complicated than not having it.
fun getFoo(): Foo? = foo.also { theFoo ->
  <http://log.info|log.info>(theFoo?.let { "Found $it" } ?: "didn't find it")
}
b

Ben Madore

09/20/2019, 2:58 PM
that’s where i started 🙂 and then was curious if perhaps there was a slightly more general solution (execute A if foo null, else B, then return foo). realize that
also
with
?:
can accomplish that.
also, your example doesn’t work exactly as written as
also
is only defined on a non-null receiver
my original was:
return foo
                ?.also { <http://log.info|log.info> { "Retrieved $it" } }
                ?: null.also { <http://log.info|log.info> { "Foo not found" } }
the
null.also
was the main bit i really didn’t like, though, it appears to actually WORK
actually nm, yours works just fine
v

Viktor Penelski

09/20/2019, 4:24 PM
alternatively a simple
if
can also be used within the initial
.also
fun getFoo(): Foo? = lookupFoo().also {
    if (foo != null) <http://log.info|log.info>("found $it!")
    else <http://log.info|log.info>("didn't find it")
}