In Scala when we do like:
val fIncr: (x: int) => x+1
My understanding is that here we are defining a function literal. Scala compiler would compile it into a class extending trait Function1 and in run-time it is instantiated and function value is assigned to fIncr.
What happens if I define a similar function as method:
def mIncr(x: Int) = x+1
Is this too compiled to a class?
Edit:
scala> val double = (i: Int) => {
| println("I am here")
| i * 2
| }
double: Int => Int = $$Lambda$1090/773348080@6ae9b2f0
scala> double(4)
I am here
res22: Int = 8
scala> val evenFunc: (Int => Boolean) = {
| println("I am here");
| (x => x % 2 == 0)
| }
I am here
evenFunc: Int => Boolean = $$Lambda$1091/373581540@a7c489a
scala> double
res23: Int => Int = $$Lambda$1090/773348080@6ae9b2f0
scala> evenFunc
res24: Int => Boolean = $$Lambda$1091/373581540@a7c489a
scala> evenFunc(10)
res25: Boolean = true
scala> def incr(x:Int) = x+1
incr: (x: Int)Int
scala> incr
<console>:13: error: missing argument list for method incr
Unapplied methods are only converted to functions when a function type is
expected.
You can make this conversion explicit by writing `incr _` or `incr(_)`
instead of `incr`.
incr
^
double and evenFunc are function variables and we have assigned function literals to them.But as output shows, when we call double, println statement is also executed.But evenFunc doesn't execute println statement, except when defined. incr is defined with keyword def, so its behaviour is as expected.