6

How do I get the function value f of an instance method?

class X(i : Int){
    def method(y : Int) = y + i
}

val x = new X(10)
val f : (Int) => Int = ?

val r = x.method(2)
val r2 = f(2)

Calling x.method(2) and f(2) would be the same method call.

Thomas Jung
  • 32,428
  • 9
  • 84
  • 114

2 Answers2

8
scala> class X(i : Int){ def method(y : Int) = y + i }

defined class X

scala> val x = new X(10)

x: X = X@15b28d8

scala> val f = x.method _

f: (Int) => Int = <function>

scala> val r = x.method(2)

r: Int = 12

scala> val r2 = f(2)

r2: Int = 12
Frank S. Thomas
  • 4,725
  • 2
  • 28
  • 47
Eastsun
  • 18,526
  • 6
  • 57
  • 81
2

this useful reference indicates that methods don't have functions, functions have methods - however if you wanted to make a function from a method perhaps this is what you want:

scala> def m1(x:Int) = x+3
m1: (Int)Int
scala> val f2 = m1 _
f2: (Int) => Int = <function>
Timothy Pratley
  • 10,586
  • 3
  • 34
  • 63