1

Can any one explain me how this two types of function Definition differ from each other. Its just a syntax? or things are bigger than I am thinking of...

Approach 1

def incriment(x:Int):Int  = x+1

Approach 2

def incriment=(x:Int) =>x+1
Biswajit
  • 323
  • 4
  • 15
  • `val` can also be used to write a function definition as in `val incr: (Int=>Int) = (x:Int)=>x+1` Note this syntax defines the parameter type(s) and return type up front, and then provides the code. – Paul Jul 18 '17 at 08:50

3 Answers3

1

scala REPL is your friend,

first one, is simply a method that takes int as input and returns int as return type.

scala> def increment1(x:Int): Int = x + 1
increment1: (x: Int)Int
             |       |
           input     return type

And method must be provided an input,

scala> increment1
<console>:12: error: missing arguments for method increment1;
follow this method with `_' if you want to treat it as a partially applied function
       increment1

scala> increment1(89)
res3: Int = 90

second one, is a method that returns a function which take int and returns int

scala> def increment2 = (x:Int) => x + 1
increment2:              Int    =>  Int
                          |          |
                        func input   func return type

//you can pass this function around, 

scala> increment2
res5: Int => Int = <function1>

to invoke a function, you can call apply method.

scala> increment2.apply(89)
res7: Int = 90

// or you can simply pass parameter within paren, which will invoke `apply`

scala> increment2(89)
res4: Int = 90

also read What is the apply function in Scala?

prayagupa
  • 30,204
  • 14
  • 155
  • 192
1

In Scala, we can skip return type if type inference is simple.

In first approach:

def increment(x: Int) : Int = x + 1

It is a function returning Integer (increment the integer argument)

But in Second approach:

def increment = (x:Int) =>x+1

This is actually a function which returns another function. The returned function can be called by a client passing integer and getting incremented integer in response

Shashank
  • 350
  • 3
  • 15
0

Those two functions are completely different.

Re. 1

def incriment(x: Int) : Int = x + 1

This is just a function that returns an Int.

Re. 2

def incriment = (x: Int) => x+1
def incriment : (Int) => Int = (x:Int) => x+1

This one is a function that returns a function which takes an Int and returns an Int ((Int) => Int). I've added type annotations to make things clear. Scala allows you to omit this, but sometimes it's recommended to add it (ex. for public methods etc.).

Arek
  • 3,106
  • 3
  • 23
  • 32