문제

Instead of using Scala Enumeration, I would like to represent my values with case classes as algebraic data type.

  sealed abstract class MeasureType
  case object Hour extends MeasureType
  case object Day extends MeasureType
  case object Week extends MeasureType
  case object Month extends MeasureType

I wonder, is it possible to create objects from a string, like with Enumeration:

MeasureType.withValue("Hour")
도움이 되었습니까?

해결책

You would need to create a singleton companion object MeasureType and write withValue method by hand using pattern matching on the argument.

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);
    } 
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top