Looking how to combine predicates. The problem is ...
# announcements
g
Looking how to combine predicates. The problem is the input is all nullable, and only when there is an input a predicate should be used. Any way to improve this, it's working correctly now.
Copy code
private fun filterFunction(direction: DType?, iban: String?, minAmount: Int?,
                           maxAmount: Int?, descrIncluded: String?): Predicate<Transaction> {
    val predicates: MutableList<Predicate<Transaction>> = ArrayList()
    direction?.let { predicates.add(Predicate { t: Transaction -> t.direction == direction }) }
    iban?.let { predicates.add(Predicate { t: Transaction -> t.iban.equals(iban) }) }
    minAmount?.let { predicates.add(Predicate { t: Transaction -> t.amount >= minAmount }) }
    maxAmount?.let { predicates.add(Predicate { t: Transaction -> t.amount <= maxAmount }) }
    descrIncluded?.let { predicates.add(Predicate { t: Transaction -> t.descr.contains(descrIncluded, true) }) }
    return Predicate { transaction: Transaction ->
        predicates.all { predicate: Predicate<Transaction> -> predicate.test(transaction) }
    }
}
e
Could do
Copy code
val predicates = listOfNotNull(
    direction?.let { Predicate { t: Transaction -> t.direction == direction } },
    // and so on and so forth
)
g
Thanks, that would indeed make it a little better
e
You also don't need to explicitly specify the lambda parameters.
Predicate { t -> t.direction == direction }
And in the example I gave above, in the
let
lambda,
direction
is accessible by
it
.