Reputation: 34463
Following function accepted more or less any collection and returned it filtered:
def filterEven[Repr](o: collection.IterableLike[Int, Repr]): Repr = {
o.filter { o =>
(o % 2) == 0
}
}
filterEven(List(1, 2, 3))
filterEven(Set(1, 2, 3))
How do I achieve the same with Scala 2.13? IterableLike
no longer exists there. Should I use higher kinded types somehow?
Upvotes: 1
Views: 183
Reputation: 34463
It seems higher kinded types together with IterableOps
can be used to achieve this:
def filterEven[CC[Int] <: IterableOps[Int, CC, CC[Int]]](o: CC[Int]): CC[Int] = {
o.filter { o =>
(o % 2) == 0
}
}
I found this more logical than the previous Repr
based solution.
Inspired by Adding custom collection operations in scala 2.13 to arbitrary collections of specific types
Upvotes: 3