Surender Raja - 1 year ago 85
Scala Question

# Scala Currying syntax explanation

I am new to scala .

I want to understand the syntax of this below code

object PlainSimple {

def main(args:Array[String])
{
println(m(3))
}

{
y=>y+x
}

}


My question is where are we saying that the add function is returning another function?

What does
Int=>Int
mean?

Inside the add function what is called
y
? Why are we using it without declaring it anywhere?

What do need to do if want multiples line inside add method?

My question is Where are we saying that the add function is returning another function?

What is Int=>Int means?

T => U as a type means "a function that takes a T and returns an U". So when we write : Int => Int at the end of the function signature, we say "this function returns a function from Int to Int".

Inside the add function what is called y ? Why are we using it without declaring it anywhere?

As an expression x => body (or (x,y,z) => body for multiple parameters) is a function literal, that is it defines an anonymous function whose parameter is named x and whose body is body. So we are declaring the parameter x by writing its name of the left side of the =>.

What do need to do if want multiples line inside add method?

You can put anything to the right of => that you could also put to the right of = when defining a method using def. So if you want your function's body to consist of multiple statements, you can use braces just like with a regular method definition:

y => {
val z = y+x
z*2
}