为什么scala Range在foreach期间不会迭代?

时间:2015-09-08 10:39:57

标签: scala for-loop foreach

考虑一下代码:

println("func")
println(builderFor)

private val LineCount: Int = 10000/*000*/
private val SymbolCount: Int = 100

private def builderFor: String = {
  val stBuilder = new StringBuilder()
  for (line <- 1 to LineCount) {
    for (symbol <- 1 to SymbolCount) {
        stBuilder.append("z" * symbol)
      }
  }
  stBuilder.toString()
}

它打印出来:

func

我已将stBuilder.append("z" * symbol)替换为println("ok")并获得了相同的结果。它接缝scala Range没有迭代,但为什么?

1 个答案:

答案 0 :(得分:1)

如果这是Appdef main(args: String*): Unit的正文,则问题是您之前致电println(builderFor)

private val LineCount: Int = 10000/*000*/
private val SymbolCount: Int = 100
代码LineCountSymbolCount中此pint的

未初始化,因此0。只需向下移动两行即可。 顺便说一下,如果你想要有z的行,那么你需要在你的行中添加换行符。

println("func")

private val LineCount: Int = 10
private val SymbolCount: Int = 10

println(builderFor)

private def builderFor: String = {
  val stBuilder = new StringBuilder()
  for (line <- 1 to LineCount) {
    for (symbol <- 1 to SymbolCount) {
      stBuilder.append("z" * symbol + "\n")
    }
  }
  stBuilder.toString()
}