Question

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.

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top