为什么函数personFromParams
返回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))
如果给 非数字值toInt
,它会返回None
for age
,但我不明白为什么在函数中捕获和处理异常时会toInt
中断。for
tryo