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
- Return the array's length.
lines.lengthis anIntholding 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:
lengthis written without parentheses. On anArray,lines.lengthreads the size directly, andlines.sizegives the same number. For the arrayArray("hello", "world", "foo")both are 3.- A
Stringhas alengthtoo, and it means something different: the number of characters."hello".lengthis 5. Herelines.lengthcounts the strings in the array, andlines(0).lengthwould count the characters in the first one. - The size of a Scala
Arrayis 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
returncould 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 inlines(0).
Edge cases and common mistakes
- An empty array.
Array[String]()has 0 lines. - Empty strings.
Array("", "")has 2 lines andArray("")has 1. A blank line is still a line. - Counting only non-empty lines. Filtering with
count(_.nonEmpty)answers a different question. OnArray("a", "", "b")it gives 2, whilelengthgives 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
| Input | Result |
|---|---|
Array("hello", "world", "foo", "bar", "baz") | 5 |
Array("", "") | 2 |
Array("") | 1 |
Array[String]() | 0 |
The next version builds on this one.
