0
votes

I defined two functions(method) in Scala REPL:

scala> val b=(x:Int)=>x+1
b: Int => Int = <function1>

scala> def c(x:Int)=x+1
c: (x: Int)Int

And the usage:

scala> b(1)
res4: Int = 2

scala> c(1)
res5: Int = 2

While both definition works, it seems that b and c have different type. And I was wondering whether there are some differences between them. Why doesn't Scala use the same type for b and c? Does anyone have ideas about this?


Not duplicate:

This question is not a duplicate of the linked question. Even though it asks about the difference between using def and val to define a function, the code example makes it clear that the asker is confused about the difference between methods and functions in Scala. The example doesn't use a def to define a function at all. – Aaron Novstrup 7 hours ago

1
One of them would generate new instance of function for every call.Dmitry Ginzburg
This question is not a duplicate of the linked question. Even though it asks about the difference between using def and val to define a function, the code example makes it clear that the asker is confused about the difference between methods and functions in Scala. The example doesn't use a def to define a function at all.Aaron Novstrup

1 Answers

0
votes

The use of def creates a method (in the case of the REPL it will create a method in some global invisible object), val instead will create an anonymous function and assign it to the symbol you specified.

When invoking those they are pretty much the same thing; when you pass them around there is a difference but Scala hides it from you by performing the ETA expansion transparently. As an example if you define this:

def isEven(i: Int): Boolean = i % 2 == 0

And then call

list.filter(isEven)

Scala is transforming that for you in a way that is similar to using the val way instead; take it as a pseudo-code as I don't know so well the scala internals but at at high level this is what happens:

list.filter((i: Int) => isEven(i))