【发布时间】:2023-09-23 06:11:01
【问题描述】:
用 def 方法和 val 函数展平 Vs flatMap:
我定义了一个名为 toInt 的 def 方法:
def toInt(s: String): Option[Int] = {
try {
Some(Integer.parseInt(s.trim))
} catch {
case e: Exception => None
}
}
这种方法适用于 flatten 和 flatMap,如下所示:
//using toInt method
val x = 1.to(5).toList
val y = List("a")
val z = x ++ y
val q = z.map(_.toString)
//using map and flatten
println(q.map(toInt).flatten)
//using flatMap
println(q.flatMap(toInt))
现在我在函数“tooInt”中使用 val 定义了相同的 toInt 功能(如在 def 方法中):
val tooInt: String => Option[Int] = s => {
try {
Some(Integer.parseInt(s.trim))
} catch {
case c: Exception => None
}
}
这适用于 flatten 但 NOT 与 flatMap 如下所示:
//using map and flatten
println(q.map(tooInt).flatten)
//using flatMap // this has error
**println(q.flatMap(tooInt))**
您能帮我理解一下吗?
最好的问候, 基兰
【问题讨论】: