Looking at this spire method's signature:
implicit def complex[A: Fractional: Trig: IsReal: Dist]: Dist[Complex[A]]
What is the meaning of [A: Fractional: Trig ...]
?
A context bound is a shorthand for expressing the common pattern of a context parameter that depends on a type parameter.
View and Context bounds are syntax sugar, and the compiler translates them using the more fundamental language constructs in the early phases of the compilation. In this section, we will review those features. In Scala, we can define methods and constructors with multiple parameter lists.
A context bound is a way of asserting the existence of an implicit value. For example, the method signature:
def complex[A : Fractional]
Means that there must be a value of type Fractional[A]
available in scope when the method is called (so that the method body can use implicitly[Fractional[A]]
to get an instance of that type). Compilation will fail if the compiler has no evidence of this fact. Context bounds are really syntactic sugar, so that the above method signature is equivalent to:
def complex[A](implicit ev: Fractional[A])
Multiple context bounds simply mean that we are making multiple such assertions about the generic parameter:
def complex[A : Fractional : Trig]
Means that there must be a values of types Fractional[A]
and Trig[A]
in scope when the method is called. So this method signature would be equivalent to:
def complex[A](implicit ev0: Fractional[A], ev1: Trig[A])
You can see this all in the REPL when you declare a method with the context bound syntax:
trait Foo[A]
trait Bar[A]
def foo[A : Foo : Bar] = ???
// foo: [A](implicit evidence$1: Foo[A], implicit evidence$2: Bar[A])Nothing
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With