我的层次结构如下所示:
trait Player
trait Player1 extends Player
trait Player2 extends Player
trait Human extends Player
trait Computer extends Player
我有一个函数文字,它将用户输入映射到type Players = Tuple2[Player1, Player2]
所在的Players类型的实例:
val initialize: Array[String] => Players = (args: Array[String]) =>
args.map(_.trim.toLowerCase) match {
case Array("x") =>
(new Player1 with Human, new Player2 with Computer)
case Array("o") =>
(new Player1 with Computer, new Player2 with Human)
case _ =>
(new Player1 with Human, new Player2 with Computer)
}
有没有办法可以让我的其他课程了解Players
,而无需全部隐含地传递玩家? e.g。
def nextPlayer(player: Player)(implicit players: Players): Player =
player match {
case _: Player1 => players._2
case _: Player2 => players._1
}
我想尽可能避免副作用,所以我没有使用过像:
object GameState {
var player1: Player = _
var player2: Player = _
}
然而,这是否必须将Players
传递给所有需要它的方法?
答案 0 :(得分:1)
将个别玩家嵌入Players
级别:
class Players(init: Array[String]) { players =>
trait Player
...
val (p1, p2) = init.map(_.trim.toLowerCase match {
case Array("x") => (new Player1 with Human, new Player2 with Human)
...
}
def nextPlayer(player: Player): Player = if (player eq p1) p2 else p1
...
}