編輯:我重寫了我的問題以闡明幷包含我想實現的目標。Scala設計幫助,抽象類或特徵上的模式匹配
我正在構建一個系統,我使用Akka發送消息。我正在使用一些小型服務來建立它。我有一個共享的核心庫,我的所有消息都駐留在案例類中。這些形成我與我的服務之間的合同。
我想做什麼就能做的是下面的,但我在抽象類信息的模式匹配出現編譯錯誤:
case class Source(serviceId: String, time: String)
case class Credentials(tenantId:String, userId: String)
sealed abstract class Message(credentials:Credentials, sources: Vector[Source])
trait FormEvent
trait MailEvent
case class FetchQuestion(questionId: String, credentials:Credentials, sources: Vector[Source]) extends Message(credentials, sources) with FormEvent
case class MailQuestion(questionId: String, credentials: Credentials, sources: Vector[Sources]) extends Message(credentials, sources) with MailEvent
def route(msg:Message, tenantId: String, sources: Vector[Source]) = msg match {
case fe:FormEvent => s"form message for $tenantId with sources $sources."
case me:MailEvent => s"mail message for $tenantId with sources $sources."
}
// Emulated Akka Receive, compilation error when matching.
def receive(a: Any) = a match {
case [email protected](credentials, srs) => route(msg.copy(sources = (srs :+ Source("routing", "justnow"))), credentials.tenantId, srs)
}
所以模式匹配的合同似乎是緊密結合的情況下類,我需要採取哪些步驟來創建一個行爲類似於案例類的超類?
下面是與提取器相同的例子。
case class Source(serviceId: String, time: String)
case class Credentials(tenantId:String, userId: String)
case class Trail(credentials: Credentials, sources: Vector[Source])
trait Message {
def trail: Trail
}
object Message {
def unapply(msg: Message) = Option(msg.trail)
}
trait FormEvent
trait MailEvent
case class FetchQuestion(questionId: String, trail:Trail) extends Message with FormEvent
case class MailQuestion(questionId: String, trail:Trail) extends Message with MailEvent
def route(msg:Message, tenantId: String, newSources: Vector[Source]) = msg match {
case fe:FormEvent => s"form message $msg for $tenantId with sources $newSources."
case me:MailEvent => s"mail message $msg for $tenantId with sources $newSources."
}
// Emulated Akka Receive, compilation error when matching.
def receive(a: Any) = a match {
case [email protected](Trail(Credentials(tenantId, _), srs)) => route(msg, tenantId, (srs :+ Source("routing", "justnow")))
}
val fq = FetchQuestion("question1", Trail(Credentials("tenant", "user"), Vector(Source("service1", "before"))))
receive(fq)
好像我正在尋找提取器。這裏是一個教程:http://danielwestheide.com/blog/2012/11/21/the-neophytes-guide-to-scala-part-1-extractors.html – Magnus