简体   繁体   中英

Context bound in Scala

I am learning Context bound in Scala.

In the below code, I am invoking multiplication operator on the integer parameter. But it errors out. 'a' is considered as type parameter; but it is actually not as per my understanding. Can someone please help.

scala> class Sample[T]
defined class Sample

scala> def method[Int:Sample](a:Int) = a * a
<console>:12: error: value * is not a member of type parameter Int
       def method[Int:Sample](a:Int) = a * a

Thanks!

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 eg 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.

The type parameter named Int does not represent concrete integer type scala.Int . Instead it is just a confusing coincidence that the type parameter was given the same name Int as the concrete type. If you give it some other name such as T

def method[T: Sample](a: T): T = a * a

the error message should make more sense. Now we see * is not defined for T since Sample type class does not yet provide such capability. Here is an example of how correct syntactic usage might look usage

trait Sample[T] {
  def mult(a: T, b: T): T
}

def method[T: Sample](a: T): T = implicitly[Sample[T]].mult(a, a)
def method[T](a: T)(implicit ev: Sample[T]): T = ev.mult(a, a)

You could also have a look at Numeric type class which provides such functionality out of the box

def method[T](a: T)(implicit num: Numeric[T]): T = num.times(a, a)

Your method has a type parameter called Int which shadows the actual Int , just like defining a normal variable would shadow something from an outer scope. The same would happen if you remove the context bound.

What you are probably trying to do is something closer to the following:

trait Sample[A] {
  def someOperation(a1: A, a2: A): A
}

implicit object IntSample extends Sample[Int] {
  override def someOperation(a1: Int, a2: Int): Int = a1 * a2
}

def method[T: Sample](t: T) = implicitly[Sample[T]].someOperation(t, t)

method(4) // compiles and returns 16
//method("4") // doesn't compile, no implicit instance of Sample[String] in scope

You can play around with this code here on Scastie.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM