Scala lambda 函数在声明参数类型时未解析?
Scala lambda function not resolved when declares the type of parameter?
在 Scala 中定义方法时,我发现了这个
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
任何人都可以解释为什么 method3 不起作用?有没有歧义?
Anonymous Functions section of the specification 涵盖了所有这些变体。相关部分是
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
.
在method3
中,函数不是块的结果表达式;在 method4
是。
编辑:哎呀,大概你的意思是为什么存在限制。我暂时保留这个答案,说明限制到底是什么,如果有人给出更好的答案,我会删除它。
一个可能的解释确实是这个限制避免了歧义:x: A => B
可以理解为一个匿名函数,它接受类型为 A
和 returns 的参数 x
对象 B
。或者可以理解为"casting"一个x
类型的变量A => B
。这两个都是有效的程序是非常罕见的,但并非不可能。考虑:
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)
这实际上编译并打印:
0
1
在 Scala 中定义方法时,我发现了这个
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
任何人都可以解释为什么 method3 不起作用?有没有歧义?
Anonymous Functions section of the specification 涵盖了所有这些变体。相关部分是
In the case of a single untyped formal parameter,
(x) => e
can be abbreviated tox => 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 tox: T => e
.
在method3
中,函数不是块的结果表达式;在 method4
是。
编辑:哎呀,大概你的意思是为什么存在限制。我暂时保留这个答案,说明限制到底是什么,如果有人给出更好的答案,我会删除它。
一个可能的解释确实是这个限制避免了歧义:x: A => B
可以理解为一个匿名函数,它接受类型为 A
和 returns 的参数 x
对象 B
。或者可以理解为"casting"一个x
类型的变量A => B
。这两个都是有效的程序是非常罕见的,但并非不可能。考虑:
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)
这实际上编译并打印:
0
1