[英]type parameter with underlying type in - Scala
Lets say I've a trait with a type A
that is a subclass of Any
and a method called nextState
that has that same type as a parameter. 可以说我有一个特征,其类型
A
是Any
的子类,而一个名为nextState
的方法具有与参数相同的类型。
trait GameEnvironment {
type A <: Any
def nextState(state: A, input: Int): (A, Boolean)
}
This trait is then extended by a class called Tetris
that overrides the type member A
and the method nextState
. 然后,此特性由名为
Tetris
的类扩展,该类重写类型成员A
和方法nextState
。
class Tetris extends GameEnvironment {
override type A = ((Array[Array[Int]]), Int)
def nextState(state: (Array[Array[Int]], Int), input: Int):
((Array[Array[Int]], Int), Boolean) = {
((state, false))
}
}
Now in another class called ReinLib
I create a GameEnvironment
, and I also have a function that takes in a parameter GameEnvironment#A
. 现在,在另一个名为
ReinLib
类中,我创建一个GameEnvironment
,并且我还有一个函数接受参数GameEnvironment#A
。
class ReinLib(val mode: String) {
val env : GameEnvironment = new Tetris()
def simulateStep(state: GameEnvironment#A, input: Int): (Boolean) =
{
env.nextState(state, input)._2
}
}
Now if I compile this code I get an error 现在,如果我编译这段代码,我会得到一个错误
type mismatch state.type (with underlying type...
类型不匹配state.type(具有基础类型...
From what I gather this happens since the compiler is not certain which type state
has. 从我的收集来看,由于编译器不确定哪种类型
state
这种情况会发生。 However I could not seem to find how to solve my issue, so I'm wondering how one would get around this. 但是我似乎找不到解决方法,因此我想知道如何解决这个问题。
The type GameEnvironment#A
is way too vague, it is essentially completely unrelated to the type of state used in env
. GameEnvironment#A
类型太含糊,基本上与env
使用的状态类型完全无关。
You probably want something like this: 您可能想要这样的东西:
trait GameEnvironment {
type A
def nextState(state: A, input: Int): (A, Boolean)
}
class Tetris extends GameEnvironment {
override type A = ((Array[Array[Int]]), Int)
def nextState(state: A, input: Int): (A, Boolean) = {
(state, false)
}
}
class ReinLib(val mode: String) {
val env: GameEnvironment = new Tetris()
def simulateStep(state: env.A, input: Int): Boolean = {
env.nextState(state, input)._2
}
}
It compiles successfully, because now env.nextState
can accept state: env.A
as parameter. 它编译成功,因为现在
env.nextState
可以接受state: env.A
作为参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.