Denis Karpov
Denis Karpov

Reputation: 75

Implicit conversion for class hierarchy with parameterized types in Scala?

I've got the following class hierarchy:

class A[T](val value: T)
class B[T](value: T) extends A[T](value)

I want to define implicit conversions and orderings for the hierarchy to be able to compare instances the following way:

new A(1) < new A(2)
new B(2) > new A(1)

and so on.

Orderding should rely on value field ordering. new B(2) > A(1) because new B(2).value > new A(1).value

Please, help!

Upvotes: 1

Views: 325

Answers (2)

Didier Dupont
Didier Dupont

Reputation: 29538

You don't tell what should happen between B(1) and A(1). Supposing they are equal

object A {
  implicit def orderingOfA[T : Ordering] : Ordering[A[T]] = Ordering.by(_.value)
}

Subtype B is mostly irrelevant, the ordering is of A, and is has to order instances of B too, as they are instance of A. Even if you decide being a B changes the comparison (maybe it breaks the tie) that would force you to write a custom ordering, but still at the same place, with the same signature.

Of course, the ordering is only defined when an orderign is available on T (hence [T : Ordering]). And it is best to define it in companion object A, which will make it available all the time, without import.

Upvotes: 2

missingfaktor
missingfaktor

Reputation: 92106

scala> class A[T](val value: T)
defined class A

scala> class B[T](value: T) extends A(value)
defined class B                                                          

scala> implicit def xord[T : Ordering] = Ordering.by((_: A[T]).value)
xord: [T](implicit evidence$1: Ordering[T])scala.math.Ordering[A[T]]

scala> import Ordering.Implicits._
import Ordering.Implicits._

scala> new A(1) < new A(2)
res2: Boolean = true

scala> new B(1) < new A(2)
res3: Boolean = true

scala> new B(2) < new A(1)
res4: Boolean = false

Upvotes: 2

Related Questions