user2726995
user2726995

Reputation: 2062

Better way to implement type class instance definitions in Scala

Is there a better / less boiler plate method of implementing instances of type classes? A simple example:

trait Equal[A]{
  def equals(a: A, b: A): Boolean = a ==b
}

object Equal{
  def apply[A: Equal] = implicitly[Equal[A]]

  implicit def IntEqual = new Equal[Int]{
    def equal(a: Int, b: Int): Boolean = a == b
  }

  implicit def OptionEqual = new Equal[Option]{
    def equal(a: Option, b: Option): Boolean = a == b

// Implicit instances for all desired types is tedious
  }

Upvotes: 2

Views: 190

Answers (1)

stew
stew

Reputation: 11366

define a method which takes a function as input and creates the typeclass instance for you:

def eqInstance[A](f: (A, A) => Boolean): Equal[A] = new Equal[A] {
  def equal(a: A, b: A): Boolean = f(a,b)
}

then your typeclass instances can be much more concise:

val intEqual = eqInstance[Int](_ == _)

Upvotes: 4

Related Questions