Reputation: 779
Based on my limited knowledge i know compiler automatically inherits the collection return type and based on that it determines the type of collection to return so in below code i want to return Option[Vector[String]]
.
I tried to experiment with below code and i get compilation error
type mismatch; found : scala.collection.immutable.Vector[String] required: Option[Vector[String]]
Code:
def readDocument(v:Option[Vector[String]]) : Option[Vector[String]] =
{
for ( a <- v;
b <- a )
yield
{
b
}
}
Upvotes: 0
Views: 142
Reputation: 1978
How about this?
def readDocument(ovs: Option[Vector[String]]): Option[Vector[String]] =
for (vs <- ovs) yield for (s <- vs) yield s
Upvotes: 0
Reputation: 53348
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))
A nested x <- xs
means flatMap
and will work only when the returned type is the same type as the most outer one.
Upvotes: 2
Reputation: 955
The for
comprehension already unboxes for you Option
so this should work
def readDocument(v:Option[Vector[String]]) : Option[Vector[String]] =
{
for ( a <- v )
yield
{
a
}
}
Upvotes: 0