How to Rewrite Function Using Context Bounds?

171 views Asked by At

Given the following Addable type-class:

scala> trait Addable[A] {
     |   def add(x: A): A
     | }
defined trait Addable

I created an instance for Int:

scala> class AddInt(x: Int) extends Addable[Int] {
     |   override def add(y: Int) = x + y
     | }
defined class AddInt

Then, I created an implicit AddInt:

scala> implicit val addInt: AddInt = new AddInt(10)
addInt: AddInt = AddInt@1f010bf0

Lastly, I defined a generic function, foo:

scala> def foo[A](x: A)(implicit ev: Addable[A]): A = ev.add(x)
foo: [A](x: A)(implicit ev: Addable[A])A

Now, I can call it with the successful implicit resolution of addInt:

scala> foo(10)
res0: Int = 20

How can I define foo using the context bound notation?

example:

def foo[A : Addable]...?

1

There are 1 answers

3
Noah On BEST ANSWER

Just define the method like you do in your own example:

def foo[A : Addable](x: A) = implicitly[Addable[A]].add(x)