0

I am new to scala and was playing around with few concepts but got stuck with following one.

If i create a method like

def sample(value:Int) = {(x:Int)=>x+1} 

This works in Scala and can be tested as sample(100), but I am not able to understand as how a method and literal here can be clubbed. Can someone explain what exactly is happening?

2

1 Answer 1

5

The parameter value here is never used and is therefore redundant. The method sample() returns a function which takes one integer parameter (which is discarded) and then adds 1 to it. So you get:

scala> def sample(value:Int) = { (x:Int) => x + 1 } sample: (value: Int)Int => Int scala> sample(100) res2: Int => Int = <function1> scala> sample(100)(10) res3: Int = 11 scala> val f = sample(99) f: Int => Int = <function1> scala> f(1) res4: Int = 2 

You could use the value parameter in the following way:

scala> def plusX(value:Int) = { (x:Int) => x + value} plusX: (value: Int)Int => Int scala> val plus10 = plusX(10) plus10: Int => Int = <function1> scala> plus10(15) res7: Int = 25 

Now plusX creates a function which takes a integer and adds the value value to it

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.