Search code examples
scalaenumerationcase-classalgebraic-data-types

Create algebraic data type case class from a string


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")

Solution

  • 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);
        } 
    }