Skip to content

Instantly share code, notes, and snippets.

@dcbriccetti
Created July 12, 2011 14:31
Show Gist options
  • Save dcbriccetti/1078092 to your computer and use it in GitHub Desktop.
Save dcbriccetti/1078092 to your computer and use it in GitHub Desktop.
Example of using implicit conversions to avoid creating anonymous inner classes
package sample
import java.util.{TimerTask, Timer}
/**
* Shows Java way of creating an anonymous inner class to supply the code for a TimerTask.
*/
object TimerDemo extends Application {
new Timer().schedule(new TimerTask {
def run() {
println("Hello")
}
}, 100L)
}
/**
* Uses an implicit conversion to simplify creating a TimerTask.
*/
object ImplicitTimerDemo extends Application {
import TimerHelper._
val newTimer = new Timer().schedule({
println("Hello")
}, 100L)
}
/**
* Implicit conversions for timers (in another source file, most likely)
*/
object TimerHelper {
/**
* Converts a block of code into a TimerTask
*/
implicit def toTimerTask(code: => Unit): TimerTask = new TimerTask {
def run() {
code
}
}
}
// Kris Nuttycombe's alternative (adapted)
case class TimerW(timer: Timer) {
def scheduleAfter(delay: Long)(code: => Unit): Unit = timer.schedule(
new TimerTask {
override def run() = code
}, delay)
}
object NuttycombeExample extends Application {
import TimerW._
(new Timer()).scheduleAfter(100L) {
println("Hello")
}
}
object TimerW {
implicit def t2tw(timer: Timer): TimerW = TimerW(timer)
}
@nuttycom
Copy link

case class TimerW(timer: Timer) {
def scheduleAfter(delay: Long)(code: => Unit): Unit = timer.schedule(
new TimerTask {
override def run() = code
}
}
}

object TimerW {
implicit def t2tw(timer: Timer) = TimerW(timer)
}

(new Timer).scheduleAfter(100L) {
println("Hello")
}

@vpatryshev
Copy link

RIght, that's how it should look like.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment