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)
將是相同的方法調用。
如何獲取實例方法的函數值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)
將是相同的方法調用。
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
this有益的借鑑表示方法不具備的功能,功能有方法 - 但是如果你想使從方法的功能或許這就是你想要什麼:
scala> def m1(x:Int) = x+3
m1: (Int)Int
scala> val f2 = m1 _
f2: (Int) => Int = <function>