如何在Scala中将类方法作为参数传递 [英] How to pass a class method as a parameter in Scala
本文介绍了如何在Scala中将类方法作为参数传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个带有一些方法的 C 类
Lets say I have a class C with some methods
def class C {
def f1():Int = ...
def f2():Int = ...
}
现在我想要一个接受两个 C 实例的方法,以及一个 C 的方法,但我不知道 f1、f2 的类型是什么,也不知道如何调用它们.我想它看起来像
Now I'd like a method that takes two instances of C, as well as a method of C, but I don't know what the types of f1, f2 are, nor how to invoke them. I'm thinking it would look something like
def cmp(first:C, second:C, t:() => Int): Boolean = {
first.t < second.t
}
这抱怨 t 不是 C 的方法.当然必须有一种方法来表达这一点.
This complains that t is not a method of C. Surely there must be a way to express this.
推荐答案
def cmp(first:C, second:C, t: C => Int): Boolean = {
t(first) < t(second)
}
那么……
val c1 = new C
val c2 = new C
cmp(c1, c2, _.f1())
cmp(c1, c2, _.f2())
这是使用匿名函数.最后两行相当于:
This is using anonymous functions. The last two lines are equivalent to:
cmp(c1, c2, {c: C => c.f1()})
cmp(c1, c2, {c: C => c.f2()})
除非您使用某种反射,否则您无法传递对方法本身的引用.
You can't pass a reference to a method per se unless you use some kind of reflection.
这篇关于如何在Scala中将类方法作为参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文