Line Filters in Kotlin

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 Kotlin that writes a capitalized version of all input text. You can use this pattern to write your own Kotlin line filters.

import java.io.BufferedReader
import java.io.InputStreamReader

fun main() {
    // Wrapping the System.in with a BufferedReader gives us a convenient
    // readLine method that reads the next line from the input.
    val reader = BufferedReader(InputStreamReader(System.`in`))

    // Read lines from stdin until there are no more
    var line: String?
    while (reader.readLine().also { line = it } != null) {
        // Convert the line to uppercase
        val ucl = line!!.uppercase()

        // Write out the uppercased line
        println(ucl)
    }

    // Check for errors during reading
    try {
        reader.close()
    } catch (e: Exception) {
        System.err.println("error: ${e.message}")
        System.exit(1)
    }
}

To try out our line filter, first make a file with a few lowercase lines.

$ echo 'hello'   > /tmp/lines
$ echo 'filter' >> /tmp/lines

Then use the line filter to get uppercase lines.

$ cat /tmp/lines | kotlin LineFilters.kt
HELLO
FILTER

In this Kotlin version:

  1. We use BufferedReader wrapped around System.in to read input lines.
  2. The readLine() method is used to read each line of input.
  3. We use a while loop to process lines until null is returned (indicating end of input).
  4. The uppercase() method is used to convert each line to uppercase.
  5. We use println() to write the uppercase line to stdout.
  6. Error handling is done using a try-catch block when closing the reader.

This Kotlin code achieves the same functionality as the original example, reading lines from standard input, converting them to uppercase, and printing the result to standard output.