Reputation: 19825
e.g.
val f1 = (a:Int) => a+1
def f2 = (a:Int) => a+1
Seems they are quite inter-changeable, are there any specific use case which I should use a particular one?
Upvotes: 3
Views: 157
Reputation: 52701
Typically one would write the def
version as:
def f2(a:Int) = a+1
If you write it they way you did, it's actually creating a method f2
that, when called, constructs a new function closure. So in both of your cases, you still have a function. But in the first case, the function gets constructed only once and stored (as f1
) for later use. But in the second case, the function gets constructed every time f2
is referenced, which is kind of a waste.
So when to prefer a function over a method? Well, you can work with a function a bit more easily in certain situations. Consider this case:
(1 to 3).map(f1 andThen f1) // totally fine
(1 to 3).map(f2 andThen f1) // "missing arguments" error
(1 to 3).map(f2 _ andThen f1) // fixed by adding "_" after the method name
So f1
is always a function and so you can call a method like andThen
on it. The variable f2
represents a method, so it doesn't expect to be used like this; it always expects to be followed by arguments. You can always turn a method into a function by following it with an underscore, but this can look a little ugly if it's not necessary.
Upvotes: 4