Alex Rivera | Logout

Differences between these three ways of defining a function in Scala

Asked 2010-09-05T16:14:36.287
92

Given three ways of expressing the same function f(a) := a + 1:

val f1 = (a:Int) => a + 1
def f2 = (a:Int) => a + 1
def f3:(Int => Int) = a => a + 1

How do these definitions differ? The REPL does not indicate any obvious differences:

scala> f1
res38: (Int) => Int = <function1>
scala> f2
res39: (Int) => Int = <function1>
scala> f3
res40: (Int) => Int = <function1>
Edit
Report

1 Answer

112

f1 is a function that takes an integer and returns an integer.

f2 is a method with zero arity that returns a function that takes an integer and returns an integer. (When you type f2 at REPL later, it becomes a call to the method f2.)

f3 is same as f2. You're just not employing type inference there.

answered 2010-09-05T16:17:29.210

Your Answer