从字符串创建代数数据类型案例类

时间:2014-04-15 06:48:46

标签: scala enumeration case-class algebraic-data-types

我不想使用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")

1 个答案:

答案 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);
    } 
}