I can implement a def with a val where the def takes no arguments:
trait T { def foo: Int }
class C(val foo: Int) extends T
Why can this not be extended to implementing a def taking N args to a val which is a FunctionN? I want it possible to implement something like:
def expensiveOperation(p: Int => Boolean) : List[Int]
With a lazy function val. Something like:
val expensiveOperation = {
val l = //get expensive list
l.filter _ //partially applied function
}
I know that this syntax does not seem to work on 2.8. Is there something I’m missing, why can I not implement a def taking parameters as a functional val?
Now, post-edits, I think I understand what you’re after. But you can’t do what you want because the type signatures don’t match.
In both cases you supply nothing and get back an Int (in this case 5). Great!
Now you supply something. But a val is just a stored object somewhere. You can supply something to the object that the label refers to, but that’s not the same as supplying something to the label ‘x’.
Here’s the def you need to use if you want a val to override it:
Now you have something that you call with no parameters and it returns something that can take a Int=>Boolean function and give you a List[Int] in return. That’s exactly what you get with the val–in both cases, you have the name of something that returns an object that has the functionality you want.
(In Scala, vals are actually implemented as hidden fields with getter methods that take no parameters and return whatever’s in the hidden field. So it really is a method just like the def is.)