convert method on type to function of type

85 views Asked by At

Is it possible to convert a method on type T to a function of type T? For example, if I have

case class T {
  def foo(u : U) : Unit = ???
}

make it possible to pass foo as the argument somef in some way to

function bar(somef : (T, U) => Unit)

So far I have pulled it out of the type like so:

def foo_(t : T, u: U) = t.foo(u)

but that isn't all too DRY, or arguably quite WET even.

1

There are 1 answers

0
Alexey Romanov On BEST ANSWER

Yes: bar(_.foo(_)) in your case. If Scala doesn't have enough information to infer types of arguments (e.g. if you had bar[T1, T2](somef: (T1, T2) => Unit)), you can use something like (_: T).foo(_: U) instead.