scala,使用类成员函数作为第一类函数

问题描述 投票:0回答:2

我想将类实例的成员函数作为第一类函数分配给变量:

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

我们可以通过分配合适的匿名函数来达到我们想要的效果。 这是唯一的方法吗? 我搜索过,但根本找不到参考资料。

function scala class member
2个回答
5
投票

使用占位符来指示其已部分应用:

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
                 ^

0
投票

在 Scala 3 中现在可以工作了

class A(val id: Int):
    def f(u:Int): Int = id + u 
        
val a = new A(5)
        
val h: Int => Int = a.f
println(h(2)) // prints 7
© www.soinside.com 2019 - 2024. All rights reserved.