[英]Scala generics; Why do I get 'Type mismatch, expected: T, actual T'
I'm working through the Coursera course, Functional Programming Principles in Scala. 我正在完成Coursera课程,即Scala中的函数式编程原理。 I'm taking the IntSet example from week3 and attempting to make it use generics.
我以第3周的IntSet示例为例,尝试使其使用泛型。 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.
我从make T <:Comparable开始,但是我找到了Ordered,所以我试图要求集合中的值要排序。 The issue is that I get a 'Type mismatch, expected: T, actual T' error in a couple of places;
问题是我在几个地方出现“类型不匹配,预期为:T,实际T”错误; 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
. 我只是想回过头来使Set类型更有用,并且遇到了这种意外行为,请
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. Ordered
也有参数类型。 You should use it as Ordered[T]
to fix it. 您应该将其用作
Ordered[T]
进行修复。 And Set
type should be T <: Ordered[T]
. 并且
Set
类型应该为T <: Ordered[T]
。 It's not Scala's problem. 这不是Scala的问题。 It's correct way of usage java's
Comparable
interface. 这是使用Java的
Comparable
接口的正确方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.