scala,使用 class 成员函数作为第一个 class 函数
scala, using class member function as first class functions
我想将 class 实例的成员函数作为第一个 class 函数分配给变量:
class A(val id:Int){ def f(u:Int)=id+u }
val a= new A(0)
val h=a.f // fails: interpreted as a.f(with missing parameter u)
val h1 = (u:Int)=>a.f(u) // OK and does what we want
我们可以通过分配一个适当的匿名函数来达到预期的效果。
这是唯一的方法吗?
我搜索了但找不到任何参考资料。
使用占位符表示已部分应用:
scala> class A(val id:Int){ def f(u:Int)=id+u }
defined class A
scala> val a = new A(0)
a: A = A@46a7a4cc
scala> val h = a.f _
h: Int => Int = <function1>
scala> h(2)
res0: Int = 2
编辑
在 REPL 打印中尝试代码
scala> val h = a.f
<console>:9: error: missing arguments for method f in class A;
follow this method with `_' if you want to treat it as a partially applied function
val h = a.f
^
我想将 class 实例的成员函数作为第一个 class 函数分配给变量:
class A(val id:Int){ def f(u:Int)=id+u }
val a= new A(0)
val h=a.f // fails: interpreted as a.f(with missing parameter u)
val h1 = (u:Int)=>a.f(u) // OK and does what we want
我们可以通过分配一个适当的匿名函数来达到预期的效果。 这是唯一的方法吗? 我搜索了但找不到任何参考资料。
使用占位符表示已部分应用:
scala> class A(val id:Int){ def f(u:Int)=id+u }
defined class A
scala> val a = new A(0)
a: A = A@46a7a4cc
scala> val h = a.f _
h: Int => Int = <function1>
scala> h(2)
res0: Int = 2
编辑
在 REPL 打印中尝试代码
scala> val h = a.f
<console>:9: error: missing arguments for method f in class A;
follow this method with `_' if you want to treat it as a partially applied function
val h = a.f
^