Cherry
Cherry

Reputation: 33514

Why scala Range is not iterated during foreach?

Consider a code:

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()
}

And it prints :

func

I have replaced stBuilder.append("z" * symbol) with println("ok") and got same result. It seams that scala Range is not iterated, but why?

Upvotes: 1

Views: 104

Answers (1)

Sascha Kolberg
Sascha Kolberg

Reputation: 7152

If this is an App or the body of a def main(args: String*): Unit, then the issue is that you call println(builderFor) before

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

at this pint in the code LineCount and SymbolCount are not initialized and thus 0. Just move it two lines down. By the way, if you want to have lines of z's, then you need to add a newline to your lines.

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()
}

Upvotes: 1

Related Questions