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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Typically one would write the
defversion as:If you write it they way you did, it’s actually creating a method
f2that, 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 (asf1) for later use. But in the second case, the function gets constructed every timef2is 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:
So
f1is always a function and so you can call a method likeandThenon it. The variablef2represents 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.