dribnet
dribnet

Reputation: 2635

Scala: implicit conversion to generate method values?

If I have the following class in Scala:

class Simple {
  def doit(a: String): Int = 42
}

And an instance of that class

o = new Simple()

Is possible to define an implicit conversion that will morph this instance and a method known at compile into a tuple like this?

Tuple2 (o, (_: Simple).doit _)

I was hoping I could come up with one for registering function callbacks in the spirit of:

doThisLater (o -> 'doit)

I functionally have my function callbacks working based on retronym's answer to a previous SO question, but it'd be great to add this thick layer of syntactic sugar.

Upvotes: 0

Views: 311

Answers (1)

Miles Sabin
Miles Sabin

Reputation: 23046

You can just eta-expand the method. Sample REPL session,

scala> case class Deferred[T, R](f : T => R)
defined class Deferred

scala> def doThisLater[T, R](f : T => R) = Deferred(f)
doThisLater: [T, R](f: T => R)Deferred[T,R]

scala> val deferred = doThisLater(o.doit _)  // eta-convert doit
deferred: Deferred[String,Int] = Deferred(<function1>)

scala> deferred.f("foo")
res0: Int = 42

Upvotes: 2

Related Questions