Created
March 15, 2013 21:17
-
-
Save sam/5173163 to your computer and use it in GitHub Desktop.
Silly example implementing an Int.times helper method.
This file contains hidden or 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
implicit class IntTimes(n:Int) { | |
def times(f: Int => Unit) { for(i <- 1 to n) f(i) } | |
// This one is optional. I'd leave it out personally. | |
// def times(f: => Unit) { for(_ <- 1 to n) f } | |
} | |
// Now you can: | |
10 times println | |
// If you added the by-name version the above wouldn't | |
// work since it'd match that. You'd have to do this | |
// instead: | |
10 times(println(_)) | |
// So passing about Int=>Unit functions is prettier | |
// if you leave off the by-name version. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Note: I used a Procedure there, and didn't specify the return value. Bad form. The Style Guide recommends (I believe) something more like this: