Reputation: 320
I am trying to implement the Filter class. My first version was the one on this question: Kotlin vararg of A to vararg of B
At that point I had not noticed the recursivity when constructing with a predicate, so I am looking for another way of implementing that.
I've changed it to this class declaration: class Filter<in T>(vararg val predicates: (T) -> Boolean)
I am trying to get this other constructor to work:
constructor(vararg filters: Filter<T>) : this(/* do something */)
I don't know how to map a vararg of filters (which contain a vararg of predicates) into a vararg of predicates that have all the predicates in each filter, especially considering that I cannot invoke any function in the filter class because it has not been initialized at that point.
Also, is there a better way to achieve what I am trying to get (a class that can be created with both an array of predicates or an array of instances of the class itself)?
Upvotes: 1
Views: 3225
Reputation: 9086
Perhaps something like this:
typealias Predicate<T> = (T) -> Boolean
class Filter<T> {
private val pred: MutableList<Predicate<T>> = mutableListOf()
constructor(vararg val predicates: Predicate<T>) {
predicates.forEach { pred.add(it) }
}
constructor(vararg filters: Filter<T>) {
filters.forEach { pred.addAll(it.pred) }
}
}
fun main(args: Array<String>) {
val f1 = Filter<String>({true}, {true})
val f2 = Filter<String>(f1, f1)
}
Upvotes: 2