【问题标题】:Expecting a Vector returned from for loop期望从 for 循环返回的 Vector
【发布时间】:2012-12-15 21:31:03
【问题描述】:

这里是 Scala 菜鸟。

这是我的简单 for 循环

  def forExampleStoreValues = {
    println(">>forExampleStoreValues");
    val retVal = for{i <- 1 to 5 if i % 2 == 0}  yield i;
    println("retVal=" + retVal);    
  }

我的期望是当我调用它时,最后一个 val 将自动返回。但是,当我从 main 调用它时,

object MainRunner {
  def main(args: Array[String]){
    println("Scala stuff!");  // println comes from Predef which definitions for anything inside a Scala compilation unit. 
    runForExamples();
  }

  def runForExamples() {
    val forLE = new ForLoopExample(); // No need to declare type.
    println("forExampleStoreValues=" +forLE.forExampleStoreValues)  
  }
}

输出是:

>>forExampleStoreValues
retVal=Vector(2, 4)
forExampleStoreValues=()

然后我尝试显式返回 retval。

  def forExampleStoreValues = {
    println(">>forExampleStoreValues");
    val retVal = for{i <- 1 to 5 if i % 2 == 0}  yield i;
    println("retVal=" + retVal);    
    return retval;
  }

这给出了:

method forExampleStoreValues has return statement; needs result type

所以我将函数签名更改为:

 def forExampleStoreValues():Vector 

给出:

Vector takes type parameters

在这个阶段,不知道该放什么,我想确保我没有做我不需要做的事情。

【问题讨论】:

    标签: scala for-loop yield


    【解决方案1】:

    您不需要显式返回。将始终返回方法中的最后一个表达式。

    def forExampleStoreValues = {
      println(">>forExampleStoreValues")
      val retVal = for{i <- 1 to 5 if i % 2 == 0}  yield i
      println("retVal=" + retVal)  
      retVal
    }
    

    这也意味着如果你以println(...) 结束你的方法,它将返回Unit 类型的(),因为这是println 的返回类型。如果你做一个显式返回(通常是因为你想提前返回),你需要指定结果类型。结果类型是Vector[Int],而不是Vector

    【讨论】:

    • 只返回forExampleStoreValues=(),就好像没有返回Vector一样。它应该打印出来。
    • 如何调用函数以及如何输出返回的内容?
    • scala> :paste // 进入粘贴模式(ctrl-D 完成) def forExampleStoreValues = { println(">>forExampleStoreValues") val retVal = for{i forExampleStoreValues >>forExampleStoreValues retVal=Vector(2, 4) res0: scala.collection.immutable.IndexedSeq[Int] = Vector(2, 4)
    • 我也是从解释器那里得到的。但是,当我从原始问题中描述的 Scala 对象调用它时,我什么也没得到。任何想法为什么?
    • 不,您应该将该对象的完整代码添加到您的问题中。
    【解决方案2】:

    返回 Scala 函数中的最后一个值。不需要显式返回。

    您的代码可以简化为for 表达式返回由编译器推断的IndexSeq[Int]

    def forExampleStoreValues = {
      for{i <- 1 to 5 if i % 2 == 0}  yield i;    
    }
    
    scala>forExampleStoreValues
    res0: scala.collection.immutable.IndexedSeq[Int] = Vector(2, 4)
    

    表达式for{i &lt;- 1 to 5 if i % 2 == 0} yield i; 返回一个Vector[Int] 的实例,它实现了特征IndexedSeq。因此,要手动指定类型,您可以将 IndexedSeq[Int] 添加到 for 表达式中。

     def forExampleStoreValues: IndexedSeq[Int] = {
       for{i <- 1 to 5 if i % 2 == 0}  yield i;    
     }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-31
      • 2018-09-07
      • 1970-01-01
      • 2011-07-05
      • 1970-01-01
      • 2021-12-17
      • 2012-02-28
      • 1970-01-01
      相关资源
      最近更新 更多