1

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?

1
  • Your question is unclear. Neither of the two methods have any parameters. Nothing is being inferred here. Commented Jul 31, 2017 at 19:55

2 Answers 2

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)

The gotcha is that in the first example a is the parameter of an anonymous function, whereas in the second example a is never declared.

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

Comments

2

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.

Comments

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.