Skip to content

Instantly share code, notes, and snippets.

@gseitz
Forked from dcbriccetti/ImplicitTimerDemo.scala
Created July 13, 2011 07:24
Show Gist options
  • Save gseitz/1079876 to your computer and use it in GitHub Desktop.
Save gseitz/1079876 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)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment