Config validation with Either
Scala
final case class Config(host: String, port: Int)
object Config {
def parse(host: String, portText: String): Either[String, Config] =
portText.toIntOption match {
case Some(port) if port > 0 && port <= 65535 =>
Right(Config(host, port))
case Some(_) =>
Left("port must be between 1 and 65535")
case None =>
Left(s"invalid port: $portText")
}
}