【问题标题】:How to return different collection with yield statement如何使用 yield 语句返回不同的集合
【发布时间】:2013-03-19 13:27:51
【问题描述】:

根据我有限的知识,我知道编译器会自动继承集合返回类型,并据此确定要返回的集合类型,因此在下面的代码中我想返回 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
     }
}

【问题讨论】:

    标签: scala


    【解决方案1】:
    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 &lt;- xs 表示flatMap,并且仅当返回的类型与the most outer one 相同时才有效。

    【讨论】:

    • for (v &lt;- Some(Vector("abc"))) yield v
    【解决方案2】:

    这个怎么样?

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

    【讨论】:

      【解决方案3】:

      for 理解已经为您解箱 Option 所以这应该可以工作

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

      【讨论】:

        猜你喜欢
        • 2012-10-24
        • 2011-02-20
        • 2020-09-30
        • 1970-01-01
        • 1970-01-01
        • 2023-03-14
        • 2020-11-14
        • 2020-06-14
        • 1970-01-01
        相关资源
        最近更新 更多