【发布时间】:2014-01-19 11:29:44
【问题描述】:
我正在尝试构建通用 for 循环。每个函数,如 func1、func2、func3 都可能返回 Some 或 None。
def func1(in: Option[String]): Option[String] = {
return in
}
def func2(in: Option[String]): Option[String] = {
return in
}
def func3(in: Option[String]): Option[String] = {
return in
}
val res = for {
x <- List(Some("hello"), None, Some("world"))
y <- func1(x)
z <- func2(y)
w <- func3(z)
} yield w
print(res)
目的是完全避免空检查。
但以下错误不允许我将参数传递给第一次调用
found : String
required: Option[String]
z <- func2(y)
^
one error found
构建这样的链的正确方法是什么?
如何避免在我的函数中保留 Option[String] 参数。我想直接用字符串操作。
【问题讨论】:
标签: scala for-loop null nullpointerexception monads