2009-09-20 58 views
6

如何獲取實例方法的函數值f在Scala中獲取實例方法的函數值

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) 

調用x.method(2)f(2)將是相同的方法調用。

回答

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

defined class X 

scala> val x = new X(10) 

x: X = [email protected] 

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 
2

this有益的借鑑表示方法不具備的功能,功能有方法 - 但是如果你想使從方法的功能或許這就是你想要什麼:

scala> def m1(x:Int) = x+3 
m1: (Int)Int 
scala> val f2 = m1 _ 
f2: (Int) => Int = <function>