1

I would like to use type classes to provide a specialized implementation for a generic class. The trouble is the class is recursive, and I did not find a way how to write the code so that is works. Here is my attempt:

object Compare {
  trait Compare[T <: Compare[T]] {
    def compare(that: T): Boolean
  }

  trait IsCompare[T] {
    def check: Boolean
  }

  trait LowerLevelImplicits {
    implicit def defaultCompare[T]: IsCompare[T] = new IsCompare[T] {
      def check = false
    }
  }

  trait Implicits extends LowerLevelImplicits {
    implicit def isCompare[T: Compare]: IsCompare[T] = new IsCompare[T] {
      def check = true
    }
  }

  case class MyClass(value: Int) extends Compare[MyClass] {
    override def compare(that: MyClass) = this equals that
  }
}

import Compare._

object Main extends App with Implicits {

  def matchArray[T: IsCompare](array: Array[T]) = {
    if (implicitly[IsCompare[T]].check) {
      println("Using isCompare")
    } else {
      println("Not using isCompare")
    }
  }


}

The error is:

Error:(17, 29) type arguments [T] do not conform to trait Compare's type parameter bounds [T <: Compare.Compare[T]]

implicit def isCompare[T: Compare]: IsCompare[T] = new IsCompare[T] {
0

1 Answer 1

2

Try to change isCompare's method signature to:

implicit def isCompare[T <: Compare[T]]: IsCompare[T] = //...
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.