[英]Scala error type mismatch
I'm trying to find another way of avoiding a type mismatch error that looks more correct than the one I'm using right now. 我正在尝试寻找另一种避免类型不匹配错误的方法,该错误看上去比我现在正在使用的更正确。
Considering the list and the function, respectively: 分别考虑列表和功能:
var l = List[Int]()
def append[U](cmd: U) = {
l = l :+ cmd
}
When interpreting the code above, I'm getting the following error: 解释上面的代码时,出现以下错误:
<console>:10: error: type mismatch;
found : List[Any]
required: List[Int]
l = l :+ cmd
^
The way I fixed it, was by modifying the append function to work like this: 我修复它的方法是通过修改append函数使其工作如下:
def append[U](cmd: U) = {
l = (l :+ cmd).asInstanceOf[List[Int]]
}
Is there a way of defining the append function without the use of asInstanceOf? 有没有一种方法可以在不使用asInstanceOf的情况下定义附加函数?
Trying to be clearer, the goal was to create the class below 为了更加清晰,目标是在下面创建类
abstract class Cstruct{
type T
var value: T
def append[U](value:U)
}
Cstruct should be built in a way that would be possible to define new classes that extends Cstruct but use different data structures for the value T. Like Cseq that uses a List of any type of elements, but should be possible to create a similar one using a Set or a Map. Cstruct的构建方式应可以定义扩展Cstruct的新类,但对值T使用不同的数据结构。就像Cseq使用任何类型的元素的List一样,但应可以使用以下方式创建类似的类:集合或地图。
class Cseq[U] (v: U) extends Cstruct{
type T = List[U]
var value: T = List[U](v)
override def append[U](cmd: U) = {
value = (value :+ cmd).asInstanceOf[T]
}
}
You get that error because your type variable U
has no constraints, it could be any type - yet you try to add a value of type U
to a list of Int
. 因为类型变量
U
没有约束,所以可能会出现任何错误,但您尝试将类型U
的值添加到Int
列表中,因此会出现此错误。
Your fix is not type-safe. 您的修复程序不是类型安全的。 It will allow you to attempt to add for example a
String
to a List[Int]
. 例如,它将允许您尝试将
String
添加到List[Int]
。 The asInstanceOf
makes the compile error go away, but you'll get a ClassCastException
at runtime if you add a wrong type of object to the list. asInstanceOf
可以使编译错误消失,但是如果将错误类型的对象添加到列表中,则会在运行时得到ClassCastException
。
Why does your method have a type parameter at all? 为什么您的方法根本没有类型参数? If the list is always a
List[Int]
, then it should just take an Int
instead of an U
: 如果列表始终是
List[Int]
,则应仅使用Int
而不是U
:
def append(cmd: Int) = {
l = l :+ cmd
}
edit - You can do this: 编辑 -您可以执行以下操作:
abstract class Cstruct[U] {
type T
var value: T
def append(value: U)
}
class Cseq[U](v: U) extends Cstruct[U] {
type T = List[U]
var value: T = List[U](v)
override def append(cmd: U) =
value = value :+ cmd
}
Note that in your own definition of Cseq[U]
, the U
in override def append[U]
is a different type parameter than the one defined at class Cseq[U]
. 请注意,在你自己定义
Cseq[U]
中, U
在override def append[U]
是不是在定义的不同类型的参数class Cseq[U]
It just happens to have the same name U
. 它恰好具有相同的名称
U
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.