Home > Back-end >  Load a String to Case Object in Scala
Load a String to Case Object in Scala

Time:01-05

I have the following objects:

  sealed abstract class ImputationStrategy(name: String)

  object ImputationStrategy {
    case object Mean extends ImputationStrategy("Mean")
    case object Median extends ImputationStrategy("Median")
    case object Mode extends ImputationStrategy("Mode")

    def fromString(imputeStrategy: String): Option[ImputationStrategy] = imputeStrategy.toLowerCase match {
      case "mean"   => Some(Mean)
      case "median" => Some(Median)
      case "mode"   => Some(Mode)
      case _        => None
    }

  }

I use this in another Config object that I load during application startup.

case class ImputerConfig(strategy: ImputationStrategy = ImputationStrategy.Mean)

But unfortunately, when I parse it like this:

  imputerConfig = ImputationStrategy.fromString(cfg.getString("imputer.strategy")).orElse(ImputationStrategy.Mean)

It says that it is expecting an Option but found ImputationStrategy.Mean.type. Is there something wrong in the way that I'm trying to parse a String to case object?

CodePudding user response:

Use getOrElse:

imputerConfig = ImputationStrategy.fromString(cfg.getString("imputer.strategy")).getOrElse(ImputationStrategy.Mean)

orElse accepts an Option. I think in you case you want to give a default object when the parsing goes wrong. Hence getOrElse is more appropriate due to the fact the it returns the value of the Option object

  •  Tags:  
  • Related