Start learning free

LESSON 9 OF 70 · PROJECTS: COMMAND-LINE TOOLS

wc v1 in Scala: Count Lines with Array length

Practice Read the full explanation

Build a tiny version of the Unix wc command. Given a list of lines, return the total number of lines as an integer.

Function signature:

def countLines(lines: Array[String]): Int

Example:

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

Output: 5

Every entry of the list is one line, even an empty string "". An empty list has 0 lines.


The number of lines is just the array's length. Use lines.length.

A one-liner:
class Solution {
    def countLines(lines: Array[String]): Int = {
        return lines.length
    }
}

STEP 1 OF 1
    Ctrl + Enter to check

    SCALA · PROJECTS: COMMAND-LINE TOOLS

    Wc V1 in Scala, explained

    Problem overview

    The Unix wc command counts things in text. This first version counts lines. The function countLines(lines: Array[String]): Int receives the lines as an array of strings and returns how many there are.

    For ["hello", "world", "foo", "bar", "baz"] the result is 5. Every entry is one line, even an empty string, and an empty array has 0 lines.

    Approach

    The input is already split into lines, so counting them means counting the entries of the array. An array knows its own size, and Scala exposes it as length. No loop and no counter variable are needed.

    The one rule to keep in mind is that an empty string still counts. The entry "" is a line with no characters in it, and length doesn't look at what the entries contain. So Array("", "") has 2 lines and Array("") has 1. Only an array with no entries at all has 0 lines.

    A counting loop gives the same answer, and it shows what length saves you:

    var count = 0
    for (line <- lines) { count += 1 }
    

    After the loop, count is 5 for the five-line example, 2 for Array("", "") and 0 for an empty array. Both versions count entries; the loop just does by hand what the array already stores. Reaching for length is the Scala habit: ask the collection, don't recount it.

    Step by step

    1. Return the array's length. lines.length is an Int holding the number of entries, which is exactly the return type the method declares.

    The solution in Scala

    class Solution {
        def countLines(lines: Array[String]): Int = {
            return lines.length
        }
    }
    

    Details worth knowing:

    • length is written without parentheses. On an Array, lines.length reads the size directly, and lines.size gives the same number. For the array Array("hello", "world", "foo") both are 3.
    • A String has a length too, and it means something different: the number of characters. "hello".length is 5. Here lines.length counts the strings in the array, and lines(0).length would count the characters in the first one.
    • The size of a Scala Array is fixed when it is created. That's why asking for its length is cheap: the number is stored, and nothing is counted at the time of the call.
    • The method's last expression is its value, so return could be left out. The lesson writes it, which is valid.
    • Write Array[String] with square brackets: they hold the element type. Elements are read with round brackets, as in lines(0).

    Edge cases and common mistakes

    • An empty array. Array[String]() has 0 lines.
    • Empty strings. Array("", "") has 2 lines and Array("") has 1. A blank line is still a line.
    • Counting only non-empty lines. Filtering with count(_.nonEmpty) answers a different question. On Array("a", "", "b") it gives 2, while length gives 3, the number the lesson asks for.
    • Counting characters instead. Summing the lengths of the strings gives the number of characters, not lines. For Array("hello", "world", "foo") that is 13, not 3.

    Testing

    InputResult
    Array("hello", "world", "foo", "bar", "baz")5
    Array("", "")2
    Array("")1
    Array[String]()0

    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