Difference between function and method

In Scala you can create functions using a so-called “function literal” E.g.

(x: Int) => x*x

Such an expression is called:

  • function literal
  • lambda function
  • anonymous function

Under the hood, that is by the Scala interpreter, this in mapped into an instance of a trait like the following:

package scala

trait Function1[A]{
    def apply(x:A):A
}

So the function

f = (x) => x*x

Is an instantiation of a class, which has an apply method. So you could write

f.apply(x) 

But also simply

f(x)

So f is an object that can be used like a function. Or a function that is an object.

Now what is a method? A method is declared with the ‘def’ keyword and there is no apply method involved.

//syntax for creating a function literal
([<parameterName> : <type> [,..]]) => {
    function body
        return [expr]
}[:return type]

val f     = (x) => x*x
//this is similar to creating for example a string literal
val mystr = "hallo"
//syntax for creating a function
def functionName([<parameterName> : <type> [,..]]):[return type]={
    function body
    return [expr]
}

Was this helpful?

0 / 0

Cookie Consent with Real Cookie Banner