Scala中for循环内的值赋值

时间:2011-06-22 23:11:57

标签: scala for-loop

此代码之间是否有任何区别:

    for(term <- term_array) {
        val list = hashmap.get(term)
        ...
    }

    for(term <- term_array; val list = hashmap.get(term)) {
        ...
    }

在循环内部我用这样的东西改变了hashmap

hashmap.put(term, string :: list)

在检查list的头部时,在使用第二个代码段时似乎已经过时了。

2 个答案:

答案 0 :(得分:19)

两者之间的区别在于,第一个是通过模式匹配创建的定义,第二个是函数文字内的值。见Programming in Scala, Section 23.1 For Expressions

  for {
    p <- persons              // a generator
    n = p.name                // a definition
    if (n startsWith "To")    // a filter
  } yield n

使用scalac -Xprint:typer <filename>.scala编译源时,您会看到真正的区别:

object X {
  val x1 = for (i <- (1 to 5); x = i*2) yield x
  val x2 = for (i <- (1 to 5)) yield { val x = i*2; x }
}

在编译器进行代码转换后,你会得到类似的东西:

private[this] val x1: scala.collection.immutable.IndexedSeq[Int] =
  scala.this.Predef.intWrapper(1).to(5).map[(Int, Int), scala.collection.immutable.IndexedSeq[(Int, Int)]](((i: Int) => {
    val x: Int = i.*(2);
    scala.Tuple2.apply[Int, Int](i, x)
  }))(immutable.this.IndexedSeq.canBuildFrom[(Int, Int)]).map[Int, scala.collection.immutable.IndexedSeq[Int]]((
    (x$1: (Int, Int)) => (x$1: (Int, Int) @unchecked) match {
      case (_1: Int, _2: Int)(Int, Int)((i @ _), (x @ _)) => x
    }))(immutable.this.IndexedSeq.canBuildFrom[Int]);

private[this] val x2: scala.collection.immutable.IndexedSeq[Int] =
  scala.this.Predef.intWrapper(1).to(5).map[Int, scala.collection.immutable.IndexedSeq[Int]](((i: Int) => {
    val x: Int = i.*(2);
    x
  }))(immutable.this.IndexedSeq.canBuildFrom[Int]);

答案 1 :(得分:8)

如果要在for语句中使用该变量,则在for循环中实例化变量是有意义的,例如:

for (i <- is; a = something; if (a)) {
   ...
}

此列表过时的原因是,这会转换为foreach来电,例如:

term_array.foreach {
   term => val list= hashmap.get(term)
} foreach {
  ...
}

所以当你到达...时,你的hashmap已经被改变了。另一个例子转换为:

term_array.foreach {
   term => val list= hashmap.get(term)
   ...
}
相关问题