Skip to content

Instantly share code, notes, and snippets.

@Allan-Gong
Created May 3, 2016 06:09
Show Gist options
  • Save Allan-Gong/ff82e382e9ce33b3a8d07d0ec0132582 to your computer and use it in GitHub Desktop.
Save Allan-Gong/ff82e382e9ce33b3a8d07d0ec0132582 to your computer and use it in GitHub Desktop.
Context bound in scala
// Consider the method tabulate which forms an array from the results of applying a given function f on a range of numbers from 0 until a given length.
// Up to Scala 2.7, tabulate could be written as follows:
def tabulate[T](len: Int, f: Int => T) = {
val xs = new Array[T](len)
for (i <- 0 until len) xs(i) = f(i)
xs
}
// In Scala 2.8 this is no longer possible, because runtime information is necessary to create the right representation of Array[T].
// One needs to provide this information by passing a ClassManifest[T] into the method as an implicit parameter:
def tabulate[T](len: Int, f: Int => T)(implicit m: ClassManifest[T]) = {
val xs = new Array[T](len)
for (i <- 0 until len) xs(i) = f(i)
xs
}
// As a shorthand form, a context bound can be used on the type parameter T instead, giving:
def tabulate[T: ClassManifest](len: Int, f: Int => T) = {
val xs = new Array[T](len)
for (i <- 0 until len) xs(i) = f(i)
xs
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment