I read Scala Functions (part of Another tour of Scala). In that post he stated:
Methods and functions are not the same thing
Here is a great post by Rob Norris which explains the difference, here is a TL;DR
Methods in Scala are not values, but functions are. You can construct a function that delegates to a method via η-expansion (triggered by the trailing underscore thingy).
with the following definition:
a method is something defined with def and a value is something you can assign to a val
In a nutshell (extract from the blog):
When we define a method we see that we cannot assign it to a val
.
scala> def add1(n: Int): Int = n + 1
add1: (n: Int)Int
scala> val f = add1
:8: error: missing arguments for method add1;
follow this method with `_' if you want to treat it as a partially applied function
val f = add1
Note also the type of add1
, which doesn’t look normal; you can’t declare a variable of type (n: Int)Int
. Methods are not values.
However, by adding the η-expansion postfix operator (η is pronounced “eta”), we can turn the method into a function value. Note the type of f
.
scala> val f = add1 _
f: Int => Int =
scala> f(3)
res0: Int = 4
The effect of _
is to perform the equivalent of the following: we construct a Function1
instance that delegates to our method.
scala> val g = new Function1[Int, Int] { def apply(n: Int): Int = add1(n) }
g: Int => Int =
scala> g(3)
res18: Int = 4