-1

Scala初心者はこちら。

これが私の単純なforループです

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

私の期待は、これを呼び出すと、最後の値が自動的に返されることです。ただし、これをメインから呼び出すと、

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

この段階では、何を入力すればよいかわかりません。必要のないことをしていないことを確認したいと思います。

4

2 に答える 2

4

明示的なリターンは必要ありません。メソッドの最後の式が常に返されます。

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

これは、メソッドを で終了すると、 の戻り値の型であるため、の型println(...)が返されることも意味します。明示的に返す場合 (通常は早く返したいため)、結果の型を指定する必要があります。結果の型はではなくです。()UnitprintlnVector[Int]Vector

于 2012-12-31T22:07:36.983 に答える
1

Scala 関数の最後の値が返されます。明示的なリターンは必要ありません。

コードは、式がコンパイラによって推論されるfora を返すこのように簡略化できます。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)

この式は、 trait を実装for{i <- 1 to 5 if i % 2 == 0} yield i;するインスタンスを返します。そのため、式に追加できる型を手動で指定します。Vector[Int]IndexedSeqIndexedSeq[Int]for

 def forExampleStoreValues: IndexedSeq[Int] = {
   for{i <- 1 to 5 if i % 2 == 0}  yield i;    
 }
于 2012-12-31T22:13:17.287 に答える