0

I have this scala code:

object C extends App{
 def sum(a:Int,b:Int,c:Int)=a+b+c

 //val d=sum
 val d=sum _
 println(d(1,2,3))
}

I have to write sum _,not sum

but In f#,I can write this:

let sum a b c=a+b+c

let d=sum

[<EntryPoint>]
let main argv = 
 printfn "%A" (d 1 2 3)

 0 // return an integer exit code

why in scala I can't just write

val d=sum
wang kai
  • 1,673
  • 3
  • 12
  • 21
  • 4
    Because `sum` [is not a **function** is a **method**](https://stackoverflow.com/questions/4839537/functions-vs-methods-in-scala). Thus, you need to turn it into a **function** to be able tp assign it. That is what the `_` does _(it is called eta-expansion)_. – Luis Miguel Mejía Suárez Jun 13 '19 at 02:50

1 Answers1

3

Scala has

  • methods (by default def is a method) and
  • functions

And they are not same.

Taking java methods as example, you can not assign methods to a variable without evaluating the method. But you can do that with function and to achieve that in scala define sum as function.

scala> def sum: (Int, Int, Int) => Int = (a, b, c) => a + b + c
sum: (Int, Int, Int) => Int

scala> val sumVal = sum
sumVal: (Int, Int, Int) => Int = $$Lambda$912/0x0000000801667840@716f94c1

scala> sumVal(1, 2, 3)
res1: Int = 6

Longer version of defining a function is,

scala>   def sum = new Function3[Int, Int, Int, Int] {
     |     def apply(a: Int, b: Int, c: Int): Int = a +b + c
     |   }
sum: (Int, Int, Int) => Int

scala> val sumVal = sum
sumVal: (Int, Int, Int) => Int = <function3>

scala> sumVal(1, 2, 3)
res2: Int = 6
prayagupa
  • 30,204
  • 14
  • 155
  • 192