scala如何推断方法的参数

a.m*_*ssa 1 scala

我偶然注意到scala可以推断某个方法参数的类型.但我不明白确切的规则.有人可以解释为什么test1方法工作以及为什么test2方法不起作用

object Test {
  def test1[A]: A => A = a => a
  def test2[A]: A = a
}
Run Code Online (Sandbox Code Playgroud)

我无法找到问题的好标题,因为我不明白这两行中发生了什么.你有什么主意吗?

Gab*_*lla 5

def test1[A]: A => A         =    a => a
              |____|              |____|

         the return type       an anonymous function
     (a function from A to A)  (`a` is a parameter of this function)


def test2[A]: A =                 a
              |                   |
        the return type      an unbound value
             (A)         (i.e. not in scope, a is not declared)
Run Code Online (Sandbox Code Playgroud)

问题是在第一个例子中a是匿名函数的参数,而在第二个例子a中从未声明.