Best way to represent a readline loop in Scala?

后端 未结 4 1187
悲哀的现实
悲哀的现实 2021-01-08 00:41

Coming from a C/C++ background, I\'m not very familiar with the functional style of programming so all my code tends to be very imperative, as in most cases I just can\'t se

4条回答
  •  -上瘾入骨i
    2021-01-08 01:06

    To add how the same can be achieved using the formerly new nio files which I vote to use because it has several advantages:

    val path: Path = Paths.get("foo.txt")
    val lines = Source.fromInputStream(Files.newInputStream(path)).getLines()
    
    // Now we can iterate the file or do anything we want,
    // e.g. using functional operations such as map. Or simply concatenate.
    val result = lines.mkString
    

    Don't forget to close the stream afterwards.

提交回复
热议问题