A Unix/Linux 'cat' function in Scala

As a quick note today, the following Scala function is more or less the same as the Unix cat command:

package iotests

object Cat extends App {
    
    import HIO.using
    import scala.io.Source

    /**
     * `getLines` returns an iterator who returns lines (NOT including newline character(s)).
     * It will treat any of \r\n, \r, or \n as a line separator (longest match).
     * If you need more refined behavior you can subclass Source#LineIterator directly.
     */
    def cat(filename: String) = using(Source.fromFile(filename)) { source => {
        for (line <- source.getLines) println(line)
    }}
    
    cat("/etc/passwd")

}

This function can be made better in a variety of ways. For instance, it’s not a pure function. It could also have some error-handling to make sure the file exists. But if the file exists it should work fine. It should work on large files because it only uses an iterator, meaning that it shouldn’t be reading more than one line of the file in at a time.

Note that this code uses the `using` function that I describe in this blog post.

FWIW, I wrote this as a test while exploring some other code, and at some point I’ll share that other code.