3

when defining method in Scala, I found this

def method1: Int => Int = (j: Int) => j  // works
def method2: Int => Int = j => j  // works
def method3: Int => Int = j: Int => j  // error
def method4: Int => Int = {j: Int => j}  // works

Can anyone explain why method3 does not work? Is there any ambiguity in it?

2 Answers 2

2

One possible explanation is indeed that this restriction avoids ambiguity: x: A => B could be understood as an anonymous function that takes a parameter x of type A and returns the object B. Or it could be understood as "casting" a variable x to the type A => B. It is very rare that both of these would be valid programs, but not impossible. Consider:

class Foo(val n: Int)
val Foo = new Foo(0)
val j: Int => Foo = new Foo(_)

def method1: Int => Foo = (j: Int) => Foo
def method2: Int => Foo = j: Int => Foo

println(method1(1).n)
println(method2(1).n)

This actually compiles and prints:

0
1
Sign up to request clarification or add additional context in comments.

1 Comment

That looks like the correct answer I am looking for. Thanks!
0

All of these variants are covered by Anonymous Functions section of the specification. The relevant part is

In the case of a single untyped formal parameter, (x) => e can be abbreviated to x => e. If an anonymous function (x : T) => e with a single typed parameter appears as the result expression of a block, it can be abbreviated to x: T => e.

In method3, the function isn't the result expression of a block; in method4 it is.

EDIT: oops, presumably you meant why the limitation is there. I'll leave this answer for now as stating what the limitation is exactly, and remove it if anyone gives a better answer.

2 Comments

Do you mind explaining what "the result expression of a block" means? Does it mean the “{}"?
@RossKeth Yes. One kind of expression in Scala is a block expression: 0, 1, or more expressions surrounded by { }. The result expression of a block is its last expression.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.