0

私の限られた知識に基づいて、コンパイラがコレクションの戻り値の型を自動的に継承し、それに基づいて返すコレクションの型を決定することを知っているので、以下のコードで戻りたいと思いOption[Vector[String]]ます。

以下のコードで実験しようとしましたが、コンパイルエラーが発生しました

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
     }
}
4

3 に答える 3

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手段and は、返された型が最も外側のflatMap型と同じ型である場合にのみ機能します。

于 2013-03-19T13:39:22.283 に答える
0

for理解はすでにあなたのためにボックス化されていないOptionので、これはうまくいくはずです

def readDocument(v:Option[Vector[String]]) : Option[Vector[String]] =    
{
  for ( a <- v )
  yield 
  {
    a
  }
}
于 2013-03-19T13:38:54.107 に答える
0

これはどう?

  def readDocument(ovs: Option[Vector[String]]): Option[Vector[String]] =
    for (vs <- ovs) yield for (s <- vs) yield s
于 2013-03-19T14:20:42.550 に答える