Context bounds are syntactic sugar for implicit generic parameters that are parameterized by some type you're using. This concept is also known as "type class". You define some generic trait, such as your Sample[T]
, and then you provide implicit(!) instances of that trait for various concrete values of T
. We call them "type class instances".
Why implicit? It's an implementation detail that Scala uses to achieve the type class mechanism; type classes also exist in e.g. Haskell, but the mechanism itself is a bit different. Anyways, you can then define a method such as your def method
which requires a type class instance for some type. And you can do this with context bound syntax, or with a more verbose and more explicit standard syntax for implicit parameters.
Your definition is using the context bound. But there is something wrong with your example, as indicated by the compilation error. Let's first see a proper example that uses the type class concept correctly.
// type class definition:
trait Sample[T] {
def getSample: T
}
// type class instance(s):
object Sample {
implicit val sampleInt: Sample[Int] =
new Sample[Int] { def getSample = 42 }
}
And now the usage:
import Sample._
// using the context bound syntax
def method1[T : Sample](t: T) = t.getSample
// not using the context bound syntax
def method2(t: T)(implicit ev: Sample[T]) = t.getSample
What we're doing is saying - there is some value t
of type T
, we don't know much about it, but what we do know is that there is a Sample
type class instance available for it. This allows us to do t.getSample
.
And now, to finally provide the answer to your problem:
In your code, you are mixing things up. Your T
is actually called Int
. You intended to use the Int
type, but what you did instead is that you named your generic parameter Int
. I could have answered this with way less text, but I figured perhaps you would find the bigger picture interesting, rather than just pointing out the mistake.