奇怪的Scala错误

时间:2010-06-13 17:23:24

标签: scala types

我尝试创建基于抽象回合的游戏和抽象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
  }
}

我认为我必须使用像Game#Player这样奇怪的类型访问器。 我得到了非常令人费解的错误。我想理解它:

[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]                 ^

2 个答案:

答案 0 :(得分:5)

def moves (player : Player)表示moves接受 Game的播放器。

Game#Player任何 Game玩家的类型。所以moves (player)是一种类型不匹配。

这是一个简单的例子,说明为什么必须不匹配。假设它不是,看看接下来会发生什么:

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

要实现这一点,我们可以更改genMove的类型。如果我们将游戏作为参数传递(并且它仍然有意义),我们可以使用路径依赖类型:

abstract class Ai[Game <: AGame] {
  def genMove (game : Game)(player : game.Player) : game.Move
  // now game.moves (player) typechecks
}

答案 1 :(得分:3)

您可以通过在game中引入抽象成员Ai来解决您的问题,然后使用此成员指定路径依赖类型:

abstract class Ai[Game <: AGame] {
  val game : Game
  def genMove (player : game.Player) : game.Move
}

class DummyAi[Game <: AGame] (val game : Game) extends Ai[Game] {
  override def genMove (player : game.Player) : game.Move = {
    game.moves (player).next
  }
}