José Villacreses
José Villacreses

Reputation: 177

Definition of functions with def

Trying in the repl:

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

scala> add(2)
res0: Int = 3

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

scala> add(2)
res1: Int = 3

I see "add" definitions differ in the type printed by the repl. I guess the first definition is something like a method and the second is something like a function value.

What are the differences of defining add in one way or the other? Is it one way preferable or discouraged?

Thank you for your help.

Upvotes: 0

Views: 71

Answers (1)

vptheron
vptheron

Reputation: 7476

There is a subtle difference between both definitions:

def add = (x: Int) => 1 + x

Each time you call add you are creating a new function Int => Int. You are basically defining a parameterless function add that returns a function Int => Int. This would be the complete signature:

def add: (Int => Int) = (x: Int) => 1 + x

A better way to write it:

val add = (x: Int) => 1 + x

Now you are defining a function Int => Int and assigning it to the value add, this will only occur once.

def add(x: Int) = 1 + x
val add = (x: Int) => 1 + x

These 2 definitions are equivalent.

Upvotes: 5

Related Questions