Best way to represent a readline loop in Scala?

后端 未结 4 1155
悲哀的现实
悲哀的现实 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条回答
  •  时光说笑
    2021-01-08 01:16

    I find that Stream is a pretty nice approach: it create a re-traversible (if needed) sequence:

    def loadLines(in: java.io.BufferedReader): Stream[String] = {
      val line = in.readLine
      if (line == null) Stream.Empty
      else Stream.cons(line, loadLines(in))
    }
    

    Each Stream element has a value (a String, line, in this case), and calls a function (loadLines(in), in this example) which will yield the next element, lazily, on demand. This makes for a good memory usage profile, especially with large data sets -- lines aren't read until they're needed, and aren't retained unless something is actually still holding onto them. Yet you can also go back to a previous Stream element and traverse forward again, yielding the exact same result.

提交回复
热议问题