I tried to create abstract turn based Game and abstract AI:
abstract class AGame {
type Player
type Move // Player inside
def actPlayer : Player
def moves (player : Player) : Iterator[Move]
def play (move : Move)
def undo ()
def isFinished : Boolean
def result (player : Player) : Double
}
abstract class Ai[Game <: AGame] {
def genMove (player : Game#Player) : Game#Move
}
class DummyGame extends AGame {
type Player = Unit
type Move = Unit
def moves (player : Player) = new Iterator[Move] {
def hasNext = false
def next = throw new Exception ("asd")
}
def actPlayer = ()
def play (move : Move) {
}
def undo () {
}
def isFinished = true
def result (player : Player) = 0
}
class DummyAi[Game <: AGame] (game : Game) extends Ai[Game] {
override def genMove (player : Game#Player) : Game#Move = {
game.moves (player).next
}
}
I thought that I have to use this strange type accessors like Game#Player. I get very puzzling error. I would like to understand it:
[error] /home/lew/Devel/CGSearch/src/main/scala/Main.scala:41: type mismatch;
[error] found : Game#Player
[error] required: DummyAi.this.game.Player
[error] game.moves (player).next
[error] ^
def moves (player : Player)
means that moves
accepts a player for this Game
.
Game#Player
is the type for a player of any Game
. So moves (player)
is a type mismatch.
Here is an easy example which shows why it must be a mismatch. Suppose it wasn't and see what happens next:
class Game2 extends DummyGame {
override type Player = Boolean
override type Move = Boolean
override def moves(player : Boolean) = new Iterator[Boolean] {...}
}
val game2: DummyGame = new Game2
// game2.Player is Boolean
val dummyGameAi = new DummyAi[DummyGame](game2)
// DummyGame#Player == Unit, so the type of genMove for Ai[DummyGame] is
// def genMove (player : Unit) : Unit
dummyGameAi.genMove(())
// this calls game2.moves(()), which doesn't typecheck
To get this to work, we can change the type of genMove
. If we pass a game as an argument (and it makes sense anyway), we can use path-dependent types:
abstract class Ai[Game <: AGame] {
def genMove (game : Game)(player : game.Player) : game.Move
// now game.moves (player) typechecks
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With