Sebastien Lorber
Sebastien Lorber

Reputation: 92140

Is providing explicitly the context bound possible in Scala?

In the following code:

   def sum[A: Monoid](xs: List[A]): A = {
     val m = implicitly[Monoid[A]]
     xs.foldLeft(m.mzero)(m.mappend)
   }

If I already have in my scope a Monoid[Int] that has mappend = _ + _, can I call my function with an explicit Monoid[Int] which has a different behavior? Or the only solution is to use a more verbose syntax with a second argument implicit monoid: Monoid[Int]?


The code exemple comes from this Scalaz tutorial: http://eed3si9n.com/learning-scalaz/sum+function.html

At the end the author shows an exemple of providing explicitly the Monoid, but he didn't use context bounds:

scala> val multiMonoid: Monoid[Int] = new Monoid[Int] {
         def mappend(a: Int, b: Int): Int = a * b
         def mzero: Int = 1
       }
multiMonoid: Monoid[Int] = $anon$1@48655fb6

scala> sum(List(1, 2, 3, 4))(multiMonoid)
res14: Int = 24

Upvotes: 3

Views: 156

Answers (1)

Régis Jean-Gilles
Régis Jean-Gilles

Reputation: 32719

Context bounds are nothing more than syntactic sugar. The following:

def sum[A: Monoid](xs: List[A])

is extactly the same as:

def sum[A](xs: List[A])(implicit evidence: Monoid[A])

This means that regardless of the way you defined your sum method (either with a context bound or with an implicit parameter), you can explicitly pass the implicit parameter as in sum(List(1, 2, 3, 4))(multiMonoid)

Upvotes: 3

Related Questions