如何使用yield语句返回不同的集合

如何使用yield语句返回不同的集合

问题描述:

基于我有限的知识,我知道编译器会自动继承集合返回类型,并基于它确定要返回的集合类型,因此在下面的代码中,我想返回Option[Vector[String]]如何使用yield语句返回不同的集合

我试着用下面的代码进行试验和我得到的编译错误

type mismatch; found : scala.collection.immutable.Vector[String] required: Option[Vector[String]] 

代码:

def readDocument(v:Option[Vector[String]]) : Option[Vector[String]] =  
{ 
    for (a <- v; 
    b <- a) 
    yield 
    { 
     b 
    } 
} 

这个怎么样?

def readDocument(ovs: Option[Vector[String]]): Option[Vector[String]] = 
    for (vs <- ovs) yield for (s <- vs) yield s 

for理解已经unboxes你Option所以这应该工作

def readDocument(v:Option[Vector[String]]) : Option[Vector[String]] =  
{ 
    for (a <- v) 
    yield 
    { 
    a 
    } 
} 

scala> for (v <- Some(Vector("abc")); e <- v) yield e 
<console>:8: error: type mismatch; 
found : scala.collection.immutable.Vector[String] 
required: Option[?] 
       for (v <- Some(Vector("abc")); e <- v) yield e 
              ^

scala> for (v <- Some(Vector("abc")); e = v) yield e 
res1: Option[scala.collection.immutable.Vector[String]] = Some(Vector(abc)) 

嵌套x <- xs表示flatMap,并且只有在返回类型与the most outer one相同时才起作用。

+0

或'for(v sourcedelica 2013-03-20 14:11:28