How to pass class method as parameter in Scala

Let's say I have class C with some methods

def class C { def f1():Int = ... def f2():Int = ... } 

Now I need a method that accepts two instances of C, as well as a C method, but I don’t know what types f1, f2 are and how to call them. I think it will look like

 def cmp(first:C, second:C, t:() => Int): Boolean = { first.t < second.t } 

It complains that t is not method C. Of course, there must be a way to express this.

+8
scala
source share
2 answers
 def cmp(first:C, second:C, t: C => Int): Boolean = { t(first) < t(second) } 

Then...

 val c1 = new C val c2 = new C cmp(c1, c2, _.f1()) cmp(c1, c2, _.f2()) 

This is the use of anonymous functions. The last two lines are equivalent:

 cmp(c1, c2, {c: C => c.f1()}) cmp(c1, c2, {c: C => c.f2()}) 

You cannot pass a reference to the per se method unless you use some kind of reflection.

+10
source share

Instead, you can simply pass method references:

 object DoOperation extends App { class C(val x: Int) { def f1():Int = x-1 def f2():Int = x+1 } def cmp(first: () => Int, second: () => Int): Boolean = { first() < second() } override def main(args: Array[String]) { println(cmp(new C(1).f1,new C(0).f2)) //prints "true" println(cmp(new C(1).f2,new C(1).f1)) //prints "false" } } 

Methods will be closed over the corresponding object instances, so the network effect will be equivalent to what you want to perform.

+8
source share

All Articles