gpt4 book ai didi

Scala抽象案例类

转载 作者:行者123 更新时间:2023-12-04 23:28:01 25 4
gpt4 key购买 nike

给定任何 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
}

最佳答案

不完全确定您要做什么......无论如何,案例类不应该被其他案例类子类化(编译器甚至应该警告您这一点)。

关于你的西装造型,像这样的东西怎么样?

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] ,而不是抛出异常;或者让西装在红心和梅花之间环绕。

关于Scala抽象案例类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9367950/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com