Biswajit
Biswajit

Reputation: 323

Function Definition In Scala

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

Upvotes: 1

Views: 220

Answers (3)

prayagupadhyay
prayagupadhyay

Reputation: 31252

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?

Upvotes: 1

Shashank
Shashank

Reputation: 370

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

Upvotes: 1

Arek
Arek

Reputation: 3176

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.).

Upvotes: 0

Related Questions