I’ve been spending quite a bit of time with Scala lately. I continue to come across the same old problems that I’ve solved a million times in Java, but now Im trying to find ways to take advantage of Scala features to solve them differently.
For example, I needed to parse a number out of a string the other day. A typical case where i had a namespaced value in a string delimited by a colon. ie. “<NS>:<Number>”
My initial instinct was to either use a regex with groups, or just split the string on the colon and pull out the second array member. Either of these solutions would have worked, and has worked countless times, but they each have their problems with correctness and verbosity.
BUT WAIT! I’m coding in Scala… there must be a better way right? There is:
My scala function uses regex groups to extract the namespace and id from the string. If the pattern matches then it evaluates to the option Some(<id>), if it doesn’t match then it evaluates to None. Simple. Readable. Type safe.