Created
July 12, 2011 14:31
-
-
Save dcbriccetti/1078092 to your computer and use it in GitHub Desktop.
Example of using implicit conversions to avoid creating anonymous inner classes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} |
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
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")
}