2013-03-19 83 views
0

基於我有限的知識,我知道編譯器會自動繼承集合返回類型,並基於它確定要返回的集合類型,因此在下面的代碼中,我想返回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 
    } 
} 

回答

0

這個怎麼樣?

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

for理解已經unboxes你Option所以這應該工作

def readDocument(v:Option[Vector[String]]) : Option[Vector[String]] =  
{ 
    for (a <- v) 
    yield 
    { 
    a 
    } 
} 
2
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 < - Some(Vector(「abc」)))yield v' – sourcedelica 2013-03-20 14:11:28