简体   繁体   中英

Scala generics; Why do I get 'Type mismatch, expected: T, actual T'

I'm working through the Coursera course, Functional Programming Principles in Scala. I'm taking the IntSet example from week3 and attempting to make it use generics. Generics have only been covered very briefly at this point, so I'm probably doing something obviously wrong, but it is not clear to me. I started by make T <: Comparable, but this I found Ordered and so I'm attempting to require values in the set to be ordered. The issue is that I get a 'Type mismatch, expected: T, actual T' error in a couple of places; I've commented the lines in the source below. That is a strange error; it found the expected type but that is an error? Note: This is NOT an assignment so I am not asking anyone to take a test for me. I just wanted to go back and make the Set type more useful and I ran into this unexpected behavior enter code here . Thank you for your help.

package week3

trait Set[T <: Ordered]
{
  def isEmpty: Boolean
  def contains(i: T): Boolean
  def include(i: T): Set[T]
  def union(that: Set[T]): Set[T]
}


/**
 * empty set
 */
class EmptySet[T <: Ordered] extends Set[T]
{
  def isEmpty = true;

  def contains(i: T): Boolean = false

  def include(i: T): Set[T] =
    new TreeSet(i, new EmptySet[T], new EmptySet[T])

  def union(that: Set[T]): Set[T] = that

  override def toString() = "{}"
}


/**
 * Immutable set
 *
 * @param value
 * @param left
 * @param right
 */
class TreeSet[T <: Ordered] (value: T, left: Set[T], right: Set[T]) extends Set[T]
{
  def isEmpty = false;

  def this(v: T) = this(v, new EmptySet[T], new EmptySet[T])

  def contains(v: T): Boolean =
  {
    if(v < value) left.contains(v)       // Type mismatch, expected: T, actual T
    else if(v > value) right.contains(v) // Type mismatch, expected: T, actual T
    else true
  }

  def include(v: T): Set[T] =
  {
    if(v < value) new TreeSet(value, left.include(v), right)      // Type mismatch, expected: T, actual T
    else if(v > value) new TreeSet(value, left, right.include(v)) // Type mismatch, expected: T, actual T
    else this
  }

  def union(that: Set[T]): Set[T] =
  {
    if(that.isEmpty) this
    else if(that == this) this
    else ((left union right) union that) include value
  }

  override def toString() = "{ " + left.toString + ' ' + value + ' ' +  right.toString + " }"
}

Ordered has parameter type too. You should use it as Ordered[T] to fix it. And Set type should be T <: Ordered[T] . It's not Scala's problem. It's correct way of usage java's Comparable interface.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM