Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between a def and a lambda'd val?

Tags:

lambda

scala

What is the difference between

def plusOne(n: Int) = n + 1

and

val plusOne = (n : Int) => n + 1
like image 930
Squidly Avatar asked Oct 29 '25 17:10

Squidly


2 Answers

What the difference really comes down to is that the first is a "method", and the second is a "function", and in Scala these two things are surprisingly different.

You could see, for example, Difference between method and function in Scala.

like image 139
Owen Avatar answered Nov 01 '25 14:11

Owen


Actually, both of them are functions.

The first one is a method or a local function, depending on where it is declared. The second one is a function value, which is an object instantiated at runtime. Methods, local functions, function values, and function literals are all flavors of functions in Scala.

See here for a chapter of Martin Odersky's book on this topic: http://www.artima.com/pins1ed/functions-and-closures.html

like image 32
hiltym Avatar answered Nov 01 '25 12:11

hiltym



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!