我有一个看起来像这样的层次结构:
trait Player
trait Player1 extends Player
trait Player2 extends Player
trait Human extends Player
trait Computer extends Player
我有一个函数文字,它将用户输入映射到 Players 类型的实例,其中type Players = Tuple2[Player1, Player2]
:
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
而不必到处隐式传递 Players?例如
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
给所有需要它的方法的唯一方法吗?