0

In the following code (mentioned in another answer, but leads to a separate question), a so-called evidence parameter is used to indicate to the compiler that the A parameter is of type string via a context bound.

case class Foo[A](a:A) { // 'A' can be substituted with any type

                      // type constraint ensures type A
  def getStringLength(implicit evidence: A =:= String) = a.length
}

But, why not simply define the class without a type parameter at all? I mean, if you parameterize the type being used, then you want a generic class; otherwise, why not just omit the type parameter as in the following?

case class Foo(a: String) {
  def getStringLength(implicit evidence: A) = a.length
}

What is an example where the context bound leads to an advantage?

Thomas Adkins
  • 412
  • 3
  • 6

0 Answers0