【发布时间】:2020-09-02 05:10:38
【问题描述】:
我开始学习 Scala,并编写了该代码。我有疑问,为什么 val 是不变的?当我第二次将它传递给同一个函数时返回其他值? scala中的纯函数怎么写?
如果计算正确的话,有什么意见吗?
import java.io.FileNotFoundException
import java.io.IOException
import scala.io.BufferedSource
import scala.io.Source.fromFile
object Main{
def main(args: Array[String]): Unit = {
val fileName: String = if(args.length == 1) args(0) else ""
try {
val file = fromFile(fileName)
/* In file tekst.txt is 4 lines */
println(s"In file $fileName is ${countLines(file)} lines")
/* In file tekst.txt is 0 lines */
println(s"In file $fileName is ${countLines(file)} lines")
file.close
}
catch{
case e: FileNotFoundException => println(s"File $fileName not found")
case _: Throwable => println("Other error")
}
}
def countLines(file: BufferedSource): Long = {
file.getLines.count(_ => true)
}
}
【问题讨论】:
标签: scala iterator immutability