0

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
     }
}
Rob
  • 4,809
  • 12
  • 48
  • 49
GammaVega
  • 729
  • 7
  • 21

3 Answers3

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))

A nested x <- xs means flatMap and will work only when the returned type is the same type as the most outer one.

Community
  • 1
  • 1
kiritsuku
  • 51,545
  • 18
  • 109
  • 133
0

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
  }
}
korefn
  • 953
  • 6
  • 16
0

How about this?

  def readDocument(ovs: Option[Vector[String]]): Option[Vector[String]] =
    for (vs <- ovs) yield for (s <- vs) yield s
john sullivan
  • 1,478
  • 1
  • 11
  • 21