Implicit conversion to Runnable?

Patrick Arnesen picture Patrick Arnesen · Jun 19, 2010 · Viewed 11.1k times · Source

As an exercise, I tried to create an implicit conversion that would accept a function and produce a Runnable. That way you could call Java methods that accept Runnable objects and use them like closures.

The implicit conversion is easy enough:

    implicit def funToRunnable(fun : Unit) = new Runnable() { def run = fun }

However I don't know how to call it. How do you pass in a no-arg function that returns Unit, without having it be evaluated at once? For example, I'd like the following to print "12" but instead it prints "21" because print("2") is evaluated at once.

    var savedFun : Runnable = null
    def save(r : Runnable) = { savedFun = r }

    save(print("2"))
    print("1")
    savedFun.run()

How do I tell the compiler to treat print("2") as the body of a function, not something to be evaluated at once? Some possibilities I tried, such as

    save(() => print("2"))

or

    save(=> print("2"))

are not legal syntax.

Answer

Patrick Arnesen picture Patrick Arnesen · Jun 19, 2010

arg, just answered my own question. I implemented the implicit conversion incorrectly. The correct implementation is

implicit def funToRunnable(fun: () => Unit) = new Runnable() { def run() = fun() }

and you call it like this:

save(() => print("2"))

This will yield "2"