Start learning free

LESSON 1 OF 70 · PROJECTS: COMMAND-LINE TOOLS

cat v1 in Scala: Print Lines with mkString

Practice Read the full explanation

Build a tiny version of the Unix cat command. Given a list of lines, return them joined by newline characters (\n) so they print one per line.

Lines can be blank, and the list can be empty (the result is then an empty string).

Function signature:

def cat(lines: List[String]): String

Example:

Input: lines = ["hello", "world", "foo"]

Output: "hello\nworld\nfoo"

When printed:
hello
world
foo

Think of the output as one big String where each input line is separated from the next by a newline character. Scala's List has a method that glues all of its elements together with a chosen separator.

Call lines.mkString("\n") — the separator goes between every pair of lines.

The full solution is a one-liner:
class Solution {
    def cat(lines: List[String]): String = {
        return lines.mkString("\n")
    }
}

STEP 1 OF 1
    Ctrl + Enter to check

    SCALA · PROJECTS: COMMAND-LINE TOOLS

    Cat V1 in Scala, explained

    Problem overview

    The Unix cat command prints lines of text one after another. This first version of the project is a function, cat, that takes a List[String] and returns one String in which the lines are separated by newline characters (\n). Printed, the result shows one line per row.

    For ["hello", "world", "foo"] the result is "hello\nworld\nfoo". Blank lines are ordinary entries, and an empty list gives an empty string.

    Approach

    A loop that appends each line and a newline works, but it leaves a newline after the last line, and you would need an extra check to avoid it. The task needs a separator between lines, not after each one. Scala's collections have a method for exactly that: mkString. Called with an argument, it joins all elements into a string and puts the argument between each pair of neighbours.

    Because the separator only appears between elements, the edge cases take care of themselves. One line has no neighbours, so no newline is added. An empty list has no elements, so the result is "".

    Here is the loop version, with the trailing newline it leaves behind:

    val sb = new StringBuilder()
    for (line <- lines) { sb.append(line + "\n") }
    

    For List("hello", "world", "foo"), sb.toString is "hello\nworld\nfoo\n", one newline too many. lines.mkString("\n") gives "hello\nworld\nfoo", which is what the lesson wants.

    Step by step

    1. Join the list with a newline. The lesson has a single step: return lines.mkString("\n"). Nothing else is needed, since the method both walks the list and places the separators.

    The solution in Scala

    class Solution {
        def cat(lines: List[String]): String = {
            return lines.mkString("\n")
        }
    }
    

    Some Scala details that matter here:

    • mkString exists on every collection, and it has three forms: with no argument it joins with nothing between the elements, mkString(sep) joins with a separator, and mkString(start, sep, end) also adds a prefix and a suffix, so List("a", "b").mkString("[", ", ", "]") gives "[a, b]".
    • The parameter type is List[String], but mkString works the same on a Vector or an Array: Vector("x", "y").mkString("-") gives "x-y".
    • The "\n" in the code is a single newline character, not a backslash followed by an n. "a\nb".length is 3.
    • The last expression of a Scala method is its value, so return is optional. The lesson uses it, which is valid. Writing just lines.mkString("\n") behaves the same.

    Edge cases and common mistakes

    • A trailing newline. The result has no newline after the last line. A loop that appends line + "\n" for every line would add one.
    • Blank lines. A blank line is an empty string in the list, and it still gets its separators. List("a", "", "b") gives "a\n\nb", which prints with an empty row in the middle.
    • A trailing blank line. List("a", "") gives "a\n": the empty last entry contributes nothing after its separator.
    • Empty list. List() gives "", and List("") also gives "".
    • Using toString instead. lines.toString gives text such as List(hello, world, foo), not the lines themselves.

    Testing

    Try these inputs in the editor above and compare the results.

    InputResult
    List("hello", "world", "foo")"hello\nworld\nfoo"
    List("only")"only"
    List("a", "", "b")"a\n\nb"
    List("a", "")"a\n"
    List()""

    The next version builds on this one.

    Keep going with Scala1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free