Line Filters in Scala
Here’s the translation of the Go line filter program to Scala, along with explanations in Markdown format suitable for Hugo:
A line filter is a common type of program that reads input on stdin, processes it, and then prints some derived result to stdout. grep
and sed
are common line filters.
Here’s an example line filter in Scala that writes a capitalized version of all input text. You can use this pattern to write your own Scala line filters.
This Scala program does the following:
We use
scala.io.StdIn
to read from standard input.We create an infinite iterator with
Iterator.continually
that tries to read a line from stdin.We use
takeWhile
to continue reading until we reach the end of the input (whenreadLine
returnsnull
) or an error occurs.For each line, we convert it to uppercase using
toUpperCase
and print it.If an error occurs while reading, we print the error message to stderr and exit the program.
To try out our line filter, first make a file with a few lowercase lines.
Then use the line filter to get uppercase lines.
This Scala version accomplishes the same task as the original program, reading lines from standard input, converting them to uppercase, and printing the result. It uses Scala’s functional features like Iterator
and pattern matching to handle the input processing and error checking.