我不想使用Scala Enumeration
,而是希望用case类代表我的值作为代数数据类型。
sealed abstract class MeasureType
case object Hour extends MeasureType
case object Day extends MeasureType
case object Week extends MeasureType
case object Month extends MeasureType
我想知道,是否可以从字符串创建对象,例如使用Enumeration
:
MeasureType.withValue("Hour")
答案 0 :(得分:2)
您需要使用参数上的模式匹配手动创建单独的伴随对象MeasureType
并编写withValue
方法。
object MeasureType {
def withValue(val : String) : MeasureType = val match {
case "Hour" => Hour
case "Day" => Day
case "Week" => Week
case "Month" => Month
case _ => throw new IllegalArgumentException("unrecognized name: " + val);
}
}