考虑一下代码:
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没有迭代,但为什么?
答案 0 :(得分:1)
如果这是App
或def main(args: String*): Unit
的正文,则问题是您之前致电println(builderFor)
private val LineCount: Int = 10000/*000*/
private val SymbolCount: Int = 100
代码LineCount
和SymbolCount
中此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()
}