Question

I have a question about creating a contravariant set represented by a function T=>Boolean that returns true if something is in the set, false otherwise. It looks like this:

class BoolSet[-T](f: T=>Boolean) {

  def contains(x:T): Boolean = f(x)

  def add(x:T): BoolSet[T] = return new BoolSet[T](((y: T)=> f(y) || y==x))

  def remove(x:T): BoolSet[T] = if(f(x)) return new BoolSet[T](((y: T)=> f(y) && y!=x)) else return this

  def union[U>:T](s : BoolSet[U]) : BoolSet[U] = return new BoolSet[U](((y: U) => this.contains(y) || s.contains(y)))

}

I'm having problems with the union function, because this.contains is a function T=>Boolean rather than U=>Boolean. How can I convert this function from taking type T to type U?

I don't understand why this doesn't work as T is a Subtype of U, so surely everything U can do T can also do?

Was it helpful?

Solution

You should change the signature of method union to

def union[U<:T](s : BoolSet[U]) : BoolSet[U]

or

def union[U>:T](s : BoolSet[U]) : BoolSet[T]

The reason is that type T is contravariant in class BoolSet, which mean BoolSet[A] is a subtype of BoolSet[B] if B <: A.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top