Skip to content

Instantly share code, notes, and snippets.

@sam
Created March 15, 2013 21:17
Show Gist options
  • Save sam/5173163 to your computer and use it in GitHub Desktop.
Save sam/5173163 to your computer and use it in GitHub Desktop.
Silly example implementing an Int.times helper method.
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.
@sam
Copy link
Author

sam commented Mar 15, 2013

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:

def times(f:Int => Unit):Unit = for(i <- 1 to n) f(i)

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