Hi guys, I have some trouble with Kotlin, more the...
# exposed
g
Hi guys, I have some trouble with Kotlin, more then exposed maybe, so it might be the wrong channel. But lets say I have the following:
Copy code
Flights
    .join(...)
    .join(...)
And then I have an optional
join
based on another parameter. One solution I guess is to use a var:
Copy code
var joins = Flights
    .join(...)
    .join(...)

if (condition) { joins = joins.join(AnotherTable...) }
Is there any feature in kotlin that make it possible to do the if in the assignment so I can keep it as a
val
? (or something like
adjustWhere
in Exposed)
Copy code
Flights
    .join(...)
    .join(...)
    .someMagicKotlinMethod {
       if (condition) ...
    }
p
.let { if (condition) it.join(other) else it }
(https://kotlinlang.org/docs/scope-functions.html#let)
k
Hey @Gustav Elmgren you can create some extension method.
Copy code
fun Join.conditional(condition: Boolean, conditionalBlock: (Join) -> Join): Join{
    return if(condition) {
        conditionalBlock.invoke(this)
    } else this
}
and use it in this way:
Copy code
NoteTable.join(EarthTable, joinType = JoinType.INNER)
    .conditional(true){
        it.crossJoin(WaterTable)
    }.conditional(false){
        it.fullJoin(SunTable)
    }.join(IceTable, joinType = JoinType.CROSS)
or version with lambda receivers
Copy code
fun Join.conditional(condition: Boolean, conditionalBlock: Join.() -> Join): Join{
    return if(condition) {
        conditionalBlock.invoke(this)
    } else this
}
Copy code
NoteTable.join(NoteTable, joinType = JoinType.INNER)
    .conditional(true){
        crossJoin(NoteTable)
    }.conditional(false){
        fullJoin(NoteTable)
    }.join(NoteTable, joinType = JoinType.CROSS)
g
Awesome, thank you!
p
a slightly more generic form would be
Copy code
inline fun <T> T.letIf(condition: Boolean, block: (T) -> T) = if(condition) let(block) else this
or
Copy code
inline fun <T> T.runIf(condition: Boolean, block: T.() -> T) = if(condition) block() else this
(named consistently with `let`/`run` ) example usage:
Copy code
Flights
    .join(...)
    .runIf(condition) { join(...) }
    .letIf(condition) { it.join(...) }
k
Just remeber about returning new value
p
They do return the new value (fixed a typo in the
letIf
) - an more (contrived) example: https://pl.kotl.in/iLYHl-LOH