What is the difference between method and function in Scala?

What's the difference between a Scala function definition using "object myfunction extends (int => int) { def apply(n:int) {...}}" and "def myfunction(n:int) {}"?

  • I am reading the code here(http://github.com/nkallen/Rowz/blob/master/src/main/scala/com/twitter/rowz/Hash.scala) but don't understand it well.

  • Answer:

    The former is a hack to define a static method without being a member of any other governing class (container). Actually `myfunction' is an Object (a singleton) which implements `apply()' method thus allowing `myfunction()' call semantic. And an illustration of first-class functions in Scala[1] via extending `int => int' function literal. (pure awesomeness). The latter will not compile at all if it's not a member of another object and remember there are no static methods in Scala. (There's something better.) So instead of having a container, why don't we make our static method "self containing". The former is a self contained static method. If we didn't have this flexibility in Scala, the implementation of a static method would be to have a companion object[2] (or a general purpose utility object) and implement the method there. A sample code below. Definition: object Utilities { def myfunction(n: Int): Int = { // doing something really important here. // serious business. } } Usage: val seriousResult = Utilities.myfunction(42); [1] Programming in Scala - Odersky, Spoon, Venners - Page 177, Section 8.3 "First-class functions" [2] Programming in Scala – Odersky, Spoon, Venners – Page 99, Section 4.3 "Singleton objects"

Berk D. Demir at Quora Visit the source

Was this solution helpful to you?

Other answers

Scala methods ("defs") are just like Java methods.  Scala also has function objects, which are really just objects with an "apply" method.  However, anObject(foo) is expanded by the compiler to anObject.apply(foo), so you can "call" either a method or an object whose name is in scope, with the same syntax.

David Greenspan

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.