0

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?

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Very strange, The error message that IntelliJ showed me was totally misleading.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.