I have declared a Value class in Scala as:
sealed abstract class Value extends Expression with Ordered[Value] {
type T <: Ordered[T]
def value: T
override def compare(that: Value): Int = { ... }
}
The reason for the type constraint T <: Ordered[T] is that I want to delegate the compare
method in Value to value: T
.
And then a concrete IntValue as:
case class IntValue(value: Int) extends Value {
type T = Int
// ...
}
However, when I try to compile this code I get the following: ''
... incompatible type in overriding
[error] type T <: Ordered[IntValue.this.T] (defined in class Value);
[error] found : Int
[error] required: <: Ordered[IntValue.this.T]
[error] (which expands to) <: Ordered[Int]
[error] type T = Int
I think that I should use some implicit conversion here, but it is not clear to me how to proceed.
The error is about incompatible type in overriding, not about implicits.
You should remove upper bound
type T <: Ordered[T]
.Int
doesn't extendOrdered
.Try type parameter rather than type member
Similar code with type member
is not possible because of
Error: illegal cyclic reference
.Scala: Abstract types vs generics
https://typelevel.org/blog/2015/07/13/type-members-parameters.html
https://www.youtube.com/watch?v=R8GksuRw3VI
https://tpolecat.github.io/2015/04/29/f-bounds.html
If you want to delegate then you should use type class
Ordering
rather than OOP traitOrdered
.Int
doesn't extendOrdered
but there is an instance ofOrdering
forInt
or
Approach with type class can be used for type member