Bet between co workers

Hi all,

what’s your take on this block?

private inline fun Boolean.ifTrue(block: () -> Unit): Boolean =
     this then this.also { block() } ?: this

private infix fun <T> Boolean.then(param: T): T? = if (this) param else null

I wanted to implement a ‘functional if-statement’. Its use will be something like this:

dataSoruce.getAll()
    .sortedBy {
         it.timestamp
     }.dropWhile {
         (condition)
             .ifTrue {
                 repository.removeById(it.id)
             }
     }

Why would anyone want to write such a construct?

And performing a side effect in a dropWhile is a bit questionable.

I personally like the idea of ifTrue and ifFalse as they IMO just look better in a functional programming environment, e.g if your condition is something. like

fun1().doSomething { some Lambda code here }.getConditionResult().ifTrue { }

I just don’t get why your implementation of ifTrue has to be so convoluted that I needed to look at it for more than a minute to understand it. Why not simply

inline fun Boolean.ifTrue(block: () -> Unit): Boolean {
    if(this) block()
    return this
}
4 Likes

Thank you very much :slight_smile:
this is exactly what I did in the start,
In the end we finished like this:

private inline fun Boolean.ifTrue(block: () -> Unit): Boolean =
    also { if (it) block() }
2 Likes