views:

189

answers:

2

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.

+2  A: 

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
+7  A: 
Welcome to Scala version 2.7.3.final (Java HotSpot(TM) Client VM, Java 1.6.0_16)

. Type in expressions to have them evaluated. Type :help for more information.

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 =

scala> val r = x.method(2)

r: Int = 12

scala> val r2 = f(2)

r2: Int = 12

scala>

Eastsun