out of curiosity: is there a nice way to abbreviat...
# announcements
t
out of curiosity: is there a nice way to abbreviate
Copy code
fun foo(): Boolean {
  val bool = isConditionMet()
  if (bool) {
     log(…)
  }
   return bool
}
j
you can use also for side effects
t
but then again if have to do the
if
i guess it could to an extension
fun Boolean.ifTrue()
j
Copy code
fun foo(): Boolean = isConditionMet().also { if (this) log(...) }
You can do a lambda for that, but the code will looks very similar
1
t
yeah thats hardly shorter and IMHO worse readability 🙂
d
Make your own alsoIfTrue?
j
it depends a lot on the eyes that are reading that, if you have the convention to knowing that also is used for side effects, you automatically read it
1
t
thank you
j
Copy code
fun Boolean.ifTrue(block: () -> Unit): Boolean {
    if (this) block()
    return this
}
Copy code
fun foo(): Boolean = isConditionMet().ifTrue { log(...) }
probably
alsoIfTrue
is a better name
1
c
There's always
Copy code
fun foo(): Boolean =
  isConditionMet()
  ?.takeIf { it }
  ?.also { log(...) }
  ?: false
but honestly, I don't think it's easier to read.
a
You could also remove the explicit return type