Reputation: 476
I would like to extend some Kotlin collection with "named" filters.
In actual project I work with (read-only) collections of data and I'm using filters a lot. I would like to create own filter for better reading of code. Right now, I have something like this and it works well...
fun main(args : Array<String>) {
val units = ArrayList<Int>()
for(i in 1..100) {
units.add(i)
}
val select = Selector(units)
select.filter { return@filter it>10 }
.inRadius(10, 15)
.filter { return@filter it%2 == 0 }
.forEach{ println(it)}
}
class Selector<E : Int>(val instance : List<E>) : Iterable<E> {
override fun iterator(): Iterator<E> {
return instance.iterator()
}
inline fun filter(predicate: (E) -> Boolean) : Selector<E> {
return Selector(instance.filter(predicate))
}
inline fun inRadius(radius : Int, position : Int) : Selector<E> {
return filter {
return@filter (it > position - radius && it < position + radius)
}
}
}
I can swap filter with inRadius method, and it will still work (thats the point of this class). But, is it the best solution (in way of memory management)? And arent there some other Stream methods (that im not using right now) that i forget to implement?
Upvotes: 0
Views: 906
Reputation: 476
After better searching...
Answer is Kotlin Extensions. Its possible to extend some class without extension or decoration it, with Kotlin Extensions.
At my problem, solution is really easy:
fun main(args : Array<String>) {
val units = ArrayList<Int>()
for(i in 1..100) {
units.add(i)
}
units.filter { return@filter it>10 }
.inRadius(10, 15)
.filter { return@filter it%2 == 0 }
.forEach{ println(it)}
}
fun List<Int>.inRadius(radius : Int, position : Int) : List<Int> {
return filter {
return@filter (it > position - radius && it < position + radius)
}
}
This will add inRadius method into List of Int types
Upvotes: 1