Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Load a String to Case Object in Scala

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  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?

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading