Scala的家族多态性

Scala的家族多态性,scala,polymorphism,Scala,Polymorphism,Scala中目前推荐的家族多态性模式是什么 在尝试游戏建模方法时,最近出现了以下解决方案: trait Game[G <: Game[G]] { type PLAYER <: Player[G] type STATE <: State[G] def players(): Set[G#PLAYER] def startState(): G#STATE } trait Player[G <: Game[G]] trait State[G <:

Scala中目前推荐的家族多态性模式是什么

在尝试游戏建模方法时,最近出现了以下解决方案:

trait Game[G <: Game[G]] {

  type PLAYER <: Player[G]
  type STATE <: State[G]

  def players(): Set[G#PLAYER]

  def startState(): G#STATE
}

trait Player[G <: Game[G]]

trait State[G <: Game[G]] {
  def player(): G#PLAYER
}
关于此设置,我有几个问题:


  • Game[G我会质疑是否需要定义特质的“外部”类别。类型
    Player
    State
    已经依赖于游戏,所以你不需要进一步限制它

    trait Game {
      type Player
      type State <: StateLike
    
      trait StateLike {
        def player: Player
      }
    
      def startState: State
    }
    
    class Poker extends Game {
      class Player
      class State extends StateLike { ... }
      val startState = new State
    }
    

    在Suereth的“Scala-In-Depth”的清单7.6中,显示了一种更高级的类似文件的特性,它具有类似的约束。该清单被用作Typeclass可以做得更好的示例。[Typeclass替代方案似乎比它所替代的版本直观得多,所以我认为我缺少了一些基本的东西。]谢谢!是的,这似乎更惯用。我提出这个问题已经有一段时间了,所以我很快就会熟悉代码和您的解决方案。您能否定义更精致的家族类型,如“TexasPoker”,其中“Player”是“Poker.Player”的子类型?
    trait Game {
      type Player
      type State <: StateLike
    
      trait StateLike {
        def player: Player
      }
    
      def startState: State
    }
    
    class Poker extends Game {
      class Player
      class State extends StateLike { ... }
      val startState = new State
    }
    
    trait PokerPlayer extends Game {
      class Player
    }
    trait PokerState extends Game with PokerPlayer {
      class State extends StateLike { ... }
    }
    class Poker extends Game with PokerPlayer with PokerState {
      val startState = ...
    }