Why does function personFromParams return None?
def personFromParams(p: Map[String, String]): Option[Person] =
for {
name <- p.get("name")
ageStr <- p.get("age")
age <- toInt(ageStr)
validStr <- p.get("valid")
valid <- toBool(validStr)
} yield { println("personFromParams()"); new Person(name, age, valid) }
def tryo[T](f: => T): Option[T] = try {Some(f)} catch {case _ => None}
def toInt(s: String): Option[Int] = tryo(s.toInt);
def toBool(s: String) = tryo(JBool.parseBoolean(s))
If give non-number value into toInt, it returns None for age, but I don’t understand
why does toInt interrupt for when the exception is caught and processed in function tryo.
Because the
forcomprehension can be equivalently written like thisFrom the scala documentation for Option.flatMap: