考虑:
def xs(c: String): Option[List[Long]] = ...
val ys: Stream[Long] = ...
现在我会写一个类似的方法:
def method(oc: Option[String]): Option[Long] = for {
c <- oc
list <- xs(c)
} yield{
for {
first <- ys.find(list contains _)
} yield first
}
但当然这不会编译,因为推断的类型是 Option[Option[Long]]。
在 scala 语法和标准库方面有没有办法获得 Option[Long]?我知道我可以进行模式匹配,但是刚刚出现了是否可以使用 for 理解来完成的问题。
感谢 Tenshi 的回答,这可以完成工作,但是我刚刚遇到了另一个问题示例:
class T
class U
class A(t: String)(implicit x: T)
def getU(a: A): Option[U] = ...
def getU_2(oc: Option[String]): Option[U] = for{
c <- oc
} yield{
implicit val someImplicit: T = new T
val a = A(c)
getU(a)
}
我可以a
在 for as 中添加:a <- Some(A(c))
但是隐含的呢?这是否意味着我的代码中的设计更改?