Reputation: 5270
I'm wondering is there a way to access the object which a high order method is called from in scala. For example say I have the following code:
val list = List(1, 3, 4, -1, 2, 0)
val filtered = list filter(_ > 0)
Say within the filter method I wanted to test the head value how would I achieve it? Something like:
val filter = list filter(_ > 0 + head)
Upvotes: 0
Views: 90
Reputation: 6533
You access it the same way you did when you accessed filter
:
val filter = list filter(_ > 0 + list.head)
I should mention that since List
is immutable, you can do this safely.
If you are chaining multiple operations on the list, then the simplest solution is to create an intermediate val
:
val first10 = x.getList() take 10
val filter = first10 filter(_ > 0 + first10.head)
As much as I love chaining operations together, this can often be more readable anyway.
Upvotes: 8
Reputation: 1848
You can always pass the result of getList to a function e.g.:
scala> def getList: List[Int] = (0 to 10).toList
getList: List[Int]
scala> getList match { case (xs: List[Int]) =>
| xs.filter(_ > xs.head + 5)
| }
res1: List[Int] = List(6, 7, 8, 9, 10)
or something slightly more interesting than x > 5
:
scala> def getList: List[Int] = (10 to 1 by -1).toList
getList: List[Int]
scala> getList
res6: List[Int] = List(10, 9, 8, 7, 6, 5, 4, 3, 2, 1)
scala> getList match { case (xs: List[Int]) =>
| xs.filter{ x => xs.head % x == 0 }
| }
res7: List[Int] = List(10, 5, 2, 1)
Note: This works fine for xs.head
, since it should be a pretty cheap operation, but if you plan looking further down into the list, like xs(5) or something, you would be traversing the list many many times.
Upvotes: 0