Scala抽象案例类

时间:2012-02-20 20:27:23

标签: scala

鉴于任何Card,我希望能够获得下一个Cards(如果它们存在)。

next()prev()函数的想法是它们分别返回下一个或上一个Suits。诉讼的顺序为:HeartsSpadesDiamondsClubs

有关更多说明,我应该这样做

// case class Card(n : Int, s : Suit)

// 1. define abstract case class Suit

// 2. define abstract case classes RedSuit and BlackSuit

// 3. define concrete case classes Hearts, Spades, Diamonds, Clubs

// 5. define abstract methods next():Suit and prev():Suit on Suit class

// 6. implement the next():Suite and prev():Suit on each of the Hearts, Diamonds,Spades and Clubs classes

// 7. implement the next():Card and prev():Card on the Card class

但首先我无法在Hearts类

上实现next()
case class Card(n: Int, s: Suit)

abstract case class Suit{
   type cardsuit <: Suit
   def next(): cardsuit
   def prev(): cardsuit
}

abstract case class RedSuit extends Suit {
   type red <: RedSuit
}

abstract case class BlackSuit extends Suit {
   type black <: BlackSuit
}

case class Hearts extends RedSuit {
   type red = Hearts
   def next(): Spade = ??? // I wanna have Spades hier 
   def prev(): Club = ??? // I wanna have Clubs hier
}

1 个答案:

答案 0 :(得分:8)

不完全确定你要做什么......在任何情况下,案例类都不应该被其他案例类子类化(编译器甚至应该警告你)。

关于你的西装的造型,这样的事情怎么样?

trait Suit {
  type ThisSuit <: Suit
  type PrevSuit <: Suit
  type NextSuit <: Suit

  def prev: PrevSuit
  def next: NextSuit
}

trait RedSuit extends Suit {
  type ThisSuit <: RedSuit
}
trait BlackSuit extends Suit {
  type ThisSuit <: BlackSuit
}

case object Hearts extends RedSuit {
  type ThisSuit = Hearts.type
  type PrevSuit = Nothing
  type NextSuit = Spades.type
  def prev = throw new NoSuchElementException
  def next = Spades
}
case object Spades extends BlackSuit {
  type ThisSuit = Spades.type
  type PrevSuit = Hearts.type
  type NextSuit = Diamonds.type
  def prev = Hearts
  def next = Diamonds
}
case object Diamonds extends RedSuit {
  type ThisSuit = Diamonds.type
  type PrevSuit = Spades.type
  type NextSuit = Clubs.type
  def prev = Spades
  def next = Clubs
}
case object Clubs extends BlackSuit {
  type ThisSuit = Clubs.type
  type PrevSuit = Diamonds.type
  type NextSuit = Nothing
  def prev = Diamonds
  def next = throw new NoSuchElementException
}

您可能希望prevnext分别返回Option[PrevSuit]Option[NextSuit],而不是抛出异常;或者让西装环绕心和俱乐部。