Related: How do you assign a function to a value in Scala?
Given:
class Foo{
def bar = println("bar")
def bat = println("bat")
}
How do I create a fnRef such that it points to either Foo.bar or Foo.bat?
def deepFunction(foos : List[Foo], fnRef : ()=>Unit) = {
foos.map(_.fnRef) //May call either bar or bat
}
Bonus: Is it possible to constrain the fnRef so that it’s only methods of that signature within the Foo class?
You don’t. 🙂 Instead you write your code in terms of first class functions. What makes this nice in Scala is that it will create a function literal from
_.methodthat’s of typeT => R, whereTis the type of the parameter, andRis the method’s return type.So,
_.barand_.batwould both makeFoo => Unit:What’s really nice about this approach is that you can use any function you want, not just member functions.