This is a method with a single parameter Int
named x
, that returns an Int
(x + 1) where the return type of Int
is inferred by the compiler.
def incImplicit(x: Int) = x + 1
This is the same exact method as above, except the return type is explicit, and not inferred.
def incImplicit(x: Int): Int = x + 1
This is a parameterless method that returns a Function1[Int, Int]
(which is a function with one Int
parameter that returns an Int
).
def incAnonymous = ((x : Int) => x + 1)
i.e. the long signature looks like this:
def incAnonymous: Function1[Int, Int] = ((x : Int) => x + 1)
Or
def incAnonymous: Int => Int = ((x : Int) => x + 1)
Functionally, they are pretty much the same. If an Int => Int
is required as a parameter, say for def map(f: Int => Int)
, they will all work. When calling map(incImplicit)
, the first two (which are the same exact method, anyway) will be implicitly converted to functions by eta-expansion. map(incAnonymous)
will already have the correct signature, and would require no conversion.
incImplicit(x)
and incAnonymous(x)
will always return the same result for any x
. The only difference is that incImplicit
is one method call, and incAnonymous
is a method call that returns a function, and then the apply
method of the returned function is invoked. Generally, you would not have a method that returns a function unless you had a very good reason to do so.