Reputation: 3499
I notice when I'm trying to create an instance of a fooSemigroup, in version one the anonymous function creates an instance of fooSemigroup without instantiating a member of Foo, but when I try to do this without the SAM construct, I need to create a dummy instance of foo for the SemigroupOps to pull in the implicit value ev
.
trait Semigroup[A] {
def combine(x: A, y: A): A
}
case class Foo(v: Int)
// vs 1
implicit val fooSemigroup: Semigroup[Foo] = (x: Foo, y: Foo) => Foo(x.v + y.v)
// vs 2
class fooSemigroup(foo: Foo) extends Semigroup[Foo] {
def combine(x: Foo, y: Foo) = Foo(x.v + y.v)
}
implicit val f: fooSemigroup = Foo(0)
implicit class SemigroupOps[A](x: A) {
def +(y: A)(implicit ev: Semigroup[A]): A = ev.combine(x, y)
}
Upvotes: 0
Views: 67
Reputation: 48430
Instead of implicit class
implicit class fooSemigroup(foo: Foo) extends Semigroup[Foo] {
def combine(x: Foo, y: Foo) = Foo(x.v + y.v)
}
try implicit object
implicit object fooSemigroup extends Semigroup[Foo] {
def combine(x: Foo, y: Foo) = Foo(x.v + y.v)
}
However as per Luis' advice favour implicit val
instances over implicit object
as otherwise resolution might result in ambiguous implicit values
error, for example
trait SomeTrait[T] {
def f: T
}
trait ExtendedTrait[T] extends SomeTrait[T] {
def g: T
}
implicit object SomeStringObject extends SomeTrait[String] {
override def f: String = "from object f"
}
implicit object ExtendedStringObject extends ExtendedTrait[String] {
override def f: String = "from extended obj f"
override def g: String = "from extended obj g"
}
implicitly[SomeTrait[String]] // Error: ambiguous implicit values
where full error states
Error:(15, 77) ambiguous implicit values:
both object ExtendedStringObject in class A$A7 of type A$A7.this.ExtendedStringObject.type
and object SomeStringObject in class A$A7 of type A$A7.this.SomeStringObject.type
match expected type A$A7.this.SomeTrait[String]
def get$$instance$$res0 = /* ###worksheet### generated $$end$$ */ implicitly[SomeTrait[String]];}
^
Upvotes: 4