A colleague the other day need to write a test that checked a string to ensure it was all digits, and happened to be using Scala for it.
An initial thought was to just iterate through the string character by character – but that was laborious and verbose…
A second thought was to just try to convert the string to an integer with toInt, then watch for the exception when it wasn’t, but even this seemed a bit heavy-handed, now that we’re getting used to Scala’s expressiveness.
After a quick experiment we came up with a cleaner solution: Use the built-in abilities to convert the string to a list, then use a partially applied function to filter the list, then take the length of the resulting all-digits string. If this length is not the same as the length of the original string, then there are non-digit characters in the string – otherwise, it’s all digits.
Here’s a transcript of a Scala command-line session trying this out:
<code> scala> "foo".toList.filter(_.isDigit).length res5: Int = 0 scala> "123".toList.filter(_.isDigit).length res6: Int = 3 scala> "abc123".toList.filter(_.isDigit).length res7: Int = 3
Of course, you can turn this into a test easily enough by
<code> assertEquals(originalString.length, originalString.toList.filter(_.isDigit).length) </code>
Now that's pretty concise