https://kotlinlang.org logo
#announcements
Title
# announcements
g

Gerard Klijs

12/07/2019, 2:11 PM
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

Edgars

12/07/2019, 2:22 PM
Could do
Copy code
val predicates = listOfNotNull(
    direction?.let { Predicate { t: Transaction -> t.direction == direction } },
    // and so on and so forth
)
g

Gerard Klijs

12/07/2019, 2:37 PM
Thanks, that would indeed make it a little better
e

Edgars

12/07/2019, 2:39 PM
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
.
3 Views