4 ms·
My favorite showcase of Scala to this day is pattern matching on regular expressions: val date = raw"(\d{4})-(\d{2})-(\d{2})".r "2004-01-20" match
by vvillena 2y ago
My favorite showcase of Scala to this day is pattern matching on regular expressions:
val date = raw"(\d{4})-(\d{2})-(\d{2})".r
"2004-01-20" match
case date(year, month, day) => s"$year was a good year for PLs."
This reads better than any equivalent Java or Kotlin code, while being much easier to maintain (e.g. matching against more than one regex).
- pantsforbirds 2y agoWould the kotlin equivalent just be: val dateRegex = Regex("""(\d{4})-(\d{2})-(\d{2})""") val (year, _, _) = dateRegex.matchEntire("2004-01-20")!!.destructured println("$year was a good year for PLs.") ?
- vvillena 2y agoThe Scala snippet works for all inputs, it's something you would see on a real codebase. It also scopes the regex captures within the match expression. The code also scales better for more complex cases where a string is tested against multiple regexes, or against specific captured values. I assume this Kotlin snippet would, at minimum, need to do null-checking on "matchEntire" before it finds its way to a production codebase.
- vaylian 2y agoWhat does the .r do at the end of the first line?
- vvillena 2y agoIt's a method call on a String that returns a Regex type, courtesy of the Scala standard library.
- vips7L 2y agoThis is my problem with Scala. Too many fancy things hidden behind text with no meaning. Why the hell is this ‘r’ instead of something with a name that has meaning like toRegex?
- vvillena 2y agoIt's a convenience method for a specific case where the result is already obvious, because it's called on a string literal that already looks like a regex. Any competent Scala dev reviewer would reject code that uses the "r" method on a variable. If you want a more verbose option, you can import the Regex type and write: val date = Regex(raw"(\d{4})-(\d{2})-(\d{2})") And of course, explicit type declarations can further document the code.
- vips7L 2y ago> Any competent Scala dev reviewer would reject code that uses the "r" method on a variable. Boy do I have news for you