Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding Multiple Context Bounds

Tags:

scala

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 ...]?

like image 481
Kevin Meredith Avatar asked Apr 19 '15 15:04

Kevin Meredith


People also ask

What does context bound mean?

A context bound is a shorthand for expressing the common pattern of a context parameter that depends on a type parameter.

What are Scala context and view bounds?

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.


1 Answers

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
like image 151
Ben Reich Avatar answered Dec 16 '22 00:12

Ben Reich