gpt4 book ai didi

scala - 为什么 'None' 会中断包含 'for' 的 'Option' 理解?

转载 作者:行者123 更新时间:2023-12-02 01:14:04 26 4
gpt4 key购买 nike

为什么函数 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,它会为age返回None,但我不明白为什么在函数tryo中捕获并处理异常时,toInt会中断for

最佳答案

因为for理解可以等价地写成这样

p.get("name").flatMap{
name => p.get("age").flatMap {
ageStr => toInt(ageStr).flatMap {
age => p.get("valid").flatMap {
validStr => p.get("valid").flatMap {
validStr => toBool(validStr).map{
valid => { println("personFromParams()"); new Person(name, age, valid) }
}
}
}
}
}
}

来自 Option.flatMap 的 Scala 文档:

Returns the result of applying f to this Option's value if this Option is nonempty. Returns None if this Option is empty. Slightly different from map in that f is expected to return an Option (which could be None).

关于scala - 为什么 'None' 会中断包含 'for' 的 'Option' 理解?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13763992/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com