Functions/Methods

What is the difference between :

def plus ( x:Int,z:Int):Int = x +z

And

val plus : Int => Int = ( x:Int,z:Int ) => x +z

I mean which one is better and why

Really, the question’s not well-formed. It’s not that one is better than the other, it’s that they are different in various ways. A function can be passed around as a first-class value, used as a parameter, and so on; a method operates within the context of a particular runtime object, and (in Scala 2, at least) can do a few subtle things that a function can’t.

They’re different tools, used for different situations. Which is why it’s fairly easy to convert a method to a function…

Ok bro thx I’m still learning :slight_smile:

In general you should use a method unless you have a specific reason to use a function. Method types are much more expressive, and you can always turn a method into a function via the eta-expansion postfix operator _ if you need to. I wrote a tiresome blog post about this which you may or may not find helpful.

1 Like