Scala абстрактный класс case - PullRequest
       0

Scala абстрактный класс case

3 голосов
/ 21 февраля 2012

Учитывая любые Card Я хотел бы иметь возможность получить следующий и предыдущий Cards, если они существуют.

Идея использования функций next() и prev() заключается в том, что они возвращают следующий или предыдущий Suits соответственно. Порядок исков должен быть: Hearts, Spades, Diamonds, Clubs.

Для большей ясности, я должен сделать это

// 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

Но, во-первых, я не могу реализовать класс 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 Ответ

8 голосов
/ 21 февраля 2012

Не совсем уверен, что вы пытаетесь сделать ... В любом случае, классы прецедентов не должны быть разделены на другие классы прецедентов (компилятор должен даже предупредить вас об этом).

Что касается моделирования ваших костюмов, как на счет этого?

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
}

Вы можете захотеть, чтобы prev и next возвращали Option[PrevSuit] и Option[NextSuit] соответственно, а не создавали исключения; или заставьте костюмы обернуться между Червами и Клубами.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...