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?
Orderedis not a typeclass, but atrait, that classes or other traits inherit from to be orderable. So you can’t implicitly get an instance ofOrdered. You have to modify your type parameter to make shure, thatAextendsOrdered[A]or can be viewed as one (<%is a view bound and means there exists an implicit conversion fromAtoOrdered[A]) and then you can simply callcompare: