Two ways of defining functions in Scala. What is the difference?

The def declares a method within a surrounding object/class/trait, similar to the way you define methods in Java. You can only use defs within other objects/classes/traits. In the REPL, you cannot see the surrounding object because it’s “hidden”, but it does exist.

You cannot assign a def to a value, because the def is not a value – it’s a method in the object.

The (x: T) => x * x declares and instantiates a function object, which exists at runtime. Function objects are instances of anonymous classes which extend FunctionN traits. FunctionN traits come with an apply method. The name apply is special, because it can be omitted. Expression f(x) is desugared into f.apply(x).

The bottomline is – since function objects are runtime values which exist on the heap, you can assign them to values, variables and parameters, or return them from methods as return values.

To solve the issue of assigning methods to values (which can be useful), Scala allows you to use the placeholder character to create a function object from a method. Expression test1 _ in your example above actually creates a wrapper function around the method test1 – it is equivalent to x => test1(x).

Leave a Comment