简体   繁体   中英

What does A => A = a => a mean in scala

I found following syntax in scala which i dont understand

object Category {
    def id[A]: A => A = a => a
}

Especially this part A = a => a

Who can it be translated in a more readable syntax

This line:

def id[A]: A => A = a => a

defines a method named id which has a type argument A .

The return type of the method is A => A , which is: a function that takes an A and returns an A .

The part after the = : a => a is the body of the id method. It's a function literal for a function that takes a value a and returns the same thing a .

The part that you are specifically asking about: A = a => a is not a part by itself. The A => A is the return type of the method id , and the a => a is the body of the method. Just like with any other method, the = between these two parts separates the method declaration from the method body.

You could write the same thing like this:

def id[A]: Function1[A, A] = a => a

It's a method that returns a function which takes an A and returns another A and the function it is returning is an identity (you get a variable a of type A and just return it):

scala> object Category {
 |     def id[A]: A => A = a => a
 | }
defined module Category

scala> Category.id[Int]
res0: Int => Int = <function1>

scala> res0(0)
res2: Int = 0

Not sure what are you trying to achieve here to be honest.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM