我有以下通用案例類來對 HTTP API 中的資源進行建模(我們使用 Akka HTTP):
case class Job[Result](
id: String,
result: Option[Result] = None,
userId: String,
)
并希望指定 a 的多個命名變體Job,其中一些提供結果,而另一些則不提供:
case class FooResult(data: String)
type FooJob = Job[FooResult]
// BarJob does not have any result, thus result should be None
case class BarJob = Job[/*what do to?*/]
我的問題是,有什么方法可以定義Job為通用案例類,其中型別引數只需要在欄位為時result指定Some?我想做的是:
// result is by default None in Job, so I don't want to specify any type here
case class BarJob = Job
或者也許有更好的方法來做到這一點,而不是使用型別別名?
uj5u.com熱心網友回復:
一種選擇是使用 base traits for Jobs 有和沒有結果:
trait Job {
def id: String
def userId: String
}
trait JobWithResult[T] extends Job {
def result: T
}
case class FooResult(data: String)
case class FooJob(id: String, userId: String, result: FooResult) extends JobWithResult[FooResult]
case class BarJob(id: String, userId: String) extends Job
然后您可以使用matchon aJob查看它是否有結果。
job match {
case FooJob(id, userId, foo) => println(s"FooJob with result $foo")
case j: JobWithResult[_] => println(s"Other job with id ${j.id} with result")
case j: Job => println(s"Job with id {$j.id} without result")
}
這假設這result實際上不是可選的。
uj5u.com熱心網友回復:
正如評論中指出的那樣,這Option是“不必要的”。
我認為,這與其說是“不必要的”,不如說是指示性的……這是一種讓您無需重復宣告即可實作您想要的東西的方式。
case class Job[Result](id: String, userId: String, result: Option[Result] = None)
object Job {
def void(id: String, userId: String) = Job[Nothing](id, userId)
def apply[R](id: String, userId: String, result: R) = Job(id, userId, Option(result))
}
type FooJob = Job[FooResult]
type VoidJob = Job[Nothing]
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/486224.html
