我正在使用「案例類而不是枚舉」模式,並且想要列出每個「枚舉」的所有值以及一些方法。所以我決定不僅僅從一個密封的抽象類派生我的案例類,而是從一個叫做Lookup的超類派生所有密封的抽象類,並定義一個從中派生抽象類的伴隨對象的LookupTrait。如何製作一個可以實例化類的參數化特徵?
abstract class Lookup {
val name: String
override def toString = name
}
trait LookupTrait[T<:Lookup] {
val all: Map[String, T]
val default: T
def withName(name: String): T =
if(all.contains(name)) all(name)
else default
}
和示例查詢看起來是這樣的:
sealed case class StudyGoal(override val name: String) extends Lookup
object StudyGoal extends LookupTrait[StudyGoal] {
override val all = Map(
"present new evaluation method" -> StudyGoal("present new evaluation method"),
"evaluate existing product" -> StudyGoal("evaluate existing product"),
"develop new theoretical model" -> StudyGoal("develop new theoretical model"),
"unknown" -> StudyGoal("unknown")
)
override val default = StudyGoal("unknown")
}
我寧願只是在每個查詢的同伴對象定義字符串列表,並有特質實例的情況下類。但是,當我在Scala中發現三種不同的反射方式時 - 使用Manifest,TypeTag,並按照in the documentation所述獲得類的構造函數,它們都似乎需要有一個類的實例存在,讓他們在參數化的LookupTrait特徵中工作。
我想有這樣的:
abstract class Lookup {
val name: String
override def toString = name
}
trait LookupTrait[T<:Lookup] {
val allNames: List[String]
val default: T = //Instantiate a T using the string "unknown".
//It is OK that this string will be the same for all Lookups.
val all: Map[String, T] = allNames.map(
n => n -> //instantiate a T here, using n as the parameter
) += default
def withName(name: String): T =
if(all.contains(name)) all(name)
else default
}
sealed case class StudyGoal(override val name: String) extends Lookup
object StudyGoal extends LookupTrait[StudyGoal] {
override val allNames = List(
"present new evaluation method"),
"evaluate existing product",
"develop new theoretical model"
)
}