質問

I am trying to create a wrapper for certain Types used in my program. I also want all of these types to have a compare Method by implementing the trait Ordered[T]. I am having a problem making a compare method that determines that the type being compared implicitly implements Ordred[T].

Current Attempt:

case class Value[T](someType: T) extends Ordered[T] {

  def matches(otherType: T): Boolean = {
    if(someType.getClass == otherType.getClass)
      true
    else false
  }

  override def toString() = {
    someType.toString
  }

  def compare(other: T): Int = {
    implicitly[Ordered[T]] compare other
  }
}

object Value {
  implicit def intVal(some: Int) = new Value[Int](some) {
    def compare(other: Int): Int = someType compare other
  }
  implicit def doubleVal(some: Double) = new Value[Double](some) {
    def compare(other: Double): Int = someType compare other
  }
  implicit def stringVal(some: String) = new Value[String](some) {
    def compare(other: String): Int = someType compare other
  }
  implicit def boolVal(some: Boolean) = new Value[Boolean](some) {
    def compare(other: Boolean): Int = someType compare other
  }
  implicit def dateVal(some: Date) = new Value[Date](some) {
    def compare(other: Date): Int = someType.compareTo(other)
  }
}

This is the structure I would like but I keep getting the error:

Could not find value for implicit parameter e: Ordered[T]

Is there some syntax that I'm missing?

役に立ちましたか?

解決

Ordered is not a typeclass, but a trait, that classes or other traits inherit from to be orderable. So you can't implicitly get an instance of Ordered. You have to modify your type parameter to make shure, that A extends Ordered[A] or can be viewed as one (<% is a view bound and means there exists an implicit conversion from A to Ordered[A]) and then you can simply call compare:

case class Value[A <% Ordered[A]](value: A) extends Ordered[Value[A]] {
  def compare(other: Value[A]) = value compare other.value
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top