how scala infer method's parameterss
I notice by chance that scala can infer the type of some method's parameter. But I don't understand the exact rule. Can someone explain me why the test1 method work and why the test2 method does not work
object Test {
def test1[A]: A => A = a => a
def test2[A]: A = a
}
I can't find a good title for my question since I don't understand what is happening in this two lines. Do you have any idea?
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
is a method that takes no input and returns a function A => A
. The name a
is given as the imput parameter of the funtion and the function simple reutrns a
, it's input.
test2
is a method that takes no input returns a value of type A
. The method is defined to return the variable named a
but that variable has never been declared so you get an error. you could redefine the method to be def test2[A](a: A): A = a
and it would work, because now a
has been declared as a variable of type A
, it is the parameter of the method.
上一篇: scala中的参数类型推断
下一篇: scala如何推断方法的参数