- About Scala
- Documentation
- Code Examples
- Software
- Scala Developers
Confusing type error with covariance and view bounds
Sun, 2012-02-05, 19:40
Hi,
I'm trying to write a simple implementation of a functional binary tree in Scala. I've run into a type error that I don't quite understand.
I'm trying to write a simple implementation of a functional binary tree in Scala. I've run into a type error that I don't quite understand.
sealed abstract class UnbalancedSet[+T] {
def insert[U >: T <% Ordered[U]](x: U): UnbalancedSet[U]
def member(x: T): Boolean
}
case object EmptyUnbalancedSet extends UnbalancedSet[Nothing] {
def insert[U <% Ordered[U]](x: U) = NonEmptyUnbalancedSet(this, x, this)
def member(x: Any) = false
}
final case class NonEmptyUnbalancedSet[+T]
(left: UnbalancedSet[T], value: T, right: UnbalancedSet[T]) extends UnbalancedSet[T] {
def insert[U >: T <% Ordered[U]](x: U) =
if (x < value) NonEmptyUnbalancedSet(left insert x, value, right)
else if (x > value) NonEmptyUnbalancedSet(left, value, right insert x)
else this
def member[T <% Ordered[T]](x: T) =
if (x < value) left member x
else if (x > value) right member x
else true
}
This program fails to compile:
[error] /Users/jordan/PFDScala/src/main/scala/UnbalancedSet.scala:24: type mismatch;[error] found : NonEmptyUnbalancedSet.this.value.type (with underlying type T)[error] required: T[error] if (x < value) left member x[error] ^[error] /Users/jordan/PFDScala/src/main/scala/UnbalancedSet.scala:24: type mismatch;[error] found : x.type (with underlying type T)[error] required: T[error] if (x < value) left member x
... and likewise for the opposite case, if (x > value).
What is going wrong here? What does the compiler mean by "underlying type", and why is it the case that a type with underlying type T is a mismatch with type T?
Thanks,Jordan Lewis
there in a class type parameter named T and a method type parameter named T. so T != T, which leads to a confusing message
Am 05.02.2012 19:40, schrieb Jordan Lewis: