scala如何推断方法的参数

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

object Test {
  def test1[A]: A => A = a => a
  def test2[A]: A = a
}

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


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)

的疑难杂症的是,在第一个例子中a是匿名函数的参数,而在第二个例子中a是从来没有声明。


test1是不接受输入并返回函数A => A 。 名称a是作为函数的输入参数给出的,函数简单地返回a ,它是输入。

test2是一个不接受任何输入的方法,返回类型A的值。 该方法被定义为返回名为a的变量,但该变量从未被声明过,所以你会得到一个错误。 你可以将方法重新定义为def test2[A](a: A): A = a并且它可以工作,因为现在a被声明为A类型的变量,它是方法的参数。

链接地址: http://www.djcxy.com/p/38027.html

上一篇: how scala infer method's parameterss

下一篇: A compiling error about scala type inference