Mike Kraley Mike Kraley - 21 days ago 9x
Scala Question

How to pass a class method as a parameter in Scala

Lets say I have a class C with some methods

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

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

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.