Scala:Any 类型和模板类的类型不匹配问题
我的 scala 类型系统存在以下问题,目前我不知道如何解决这个问题。
基本上有以下情况:
我有一个类,我们称之为 Actor。这个类是模板化的。
class Actor[T](){
def setValue(value: T): Int = {
//do something with value
}
}
另一个类具有迭代以下类型的 HashMap 的方法:
var newValues = new HashMap[String, Any]()
此 HashMap 将包含 Int 和 String 类型的值。 HashMap 的 Key 标识一个具体的 Actor 类,并确保值的类型适合它所引用的模板化 Actor 类。
另一个类的方法迭代此 HashMap:
newValues.foreach(
kv => {
db.getActor(kv._1).setValue(kv._2) //db.getActor returns an Actor identified by kv._1
}
)
因为具体值 (kv._2) 具有与运行时收到的模板化类相同的数据类型,所以我认为 scala 引擎能够将任何类型转换为其具体值子类型 T。
但是我在编译过程中收到以下错误:
found : kv._2.type (with underlying type Any)
required: _$3 where type _$3
db.getActor(kv._1).setValue(kv._2)
有人知道如何解决这个问题吗?我认为通过使用超类型 Any 可以绕过 switch-case 并使用对象 Any 的 asInstanceOf[T] 。
希望有人能帮助我!
I have the following problem with the scala type system and I have currently no idea how to fix this.
Basically there is the follow situation:
I have a class, lets call it Actor. This class is templated.
class Actor[T](){
def setValue(value: T): Int = {
//do something with value
}
}
Another class has a method which iterates over a HashMap of the following type:
var newValues = new HashMap[String, Any]()
This HashMap will contain values of type Int and String. The Key of the HashMap identifies a concrete Actor class and ensures that the type of the value fits the templated Actor class it refers to.
A method of the other class iterates over this HashMap:
newValues.foreach(
kv => {
db.getActor(kv._1).setValue(kv._2) //db.getActor returns an Actor identified by kv._1
}
)
Because the concrete value (kv._2) has the same datatype like the templated class has recieved during runtime, I thought the scala engine would be able to cast the any-type into its concrete subtype T.
But I get the following error during compilation:
found : kv._2.type (with underlying type Any)
required: _$3 where type _$3
db.getActor(kv._1).setValue(kv._2)
Does anybody know to fix this problem? I thought by using the super-type Any it would be possible to get around a switch-case and using asInstanceOf[T] of object Any.
Hope somebody can help me!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这里的问题是:
谁说的?
编译器无法在编译时证明这确实是真的。而且,基本上,它不信任你。
您始终可以使用
asIntanceOf
告诉编译器您了解得更多——也称为将枪瞄准您的脚。我想知道 db.getActor 返回什么类型!我半猜测存在主义。The problem here is:
Says who?
The compiler couldn't prove, at compile time, that this is, indeed, true. And, basically, it doesn't trust you.
You can always use
asIntanceOf
to tell the compiler that you know better -- also known as aiming a gun at your foot. And I wonder what typedb.getActor
returns! I'm half-guessing existential.