| Well, yes, you're right – like beauty, readability is in the eye of the beholder. I've been writing a ton of Scala code lately, and my version is very Scala-like, so it looks better to me. That said, I think there are several advantages: • It's more compact, with fewer lines and fewer characters, but at least as readable • There's simple separation of concerns: it only has a single print statement – the whole range is transformed, then printed – which makes it easy to refactor later if I need to use those values for something other than printing • It's obvious that all of the cases are handled • In an amazing coincidence, it looks like code I write :) so I personally prefer it If you're implying that there are times that if/elif/else syntax is more readable than pattern matching, then yes, absolutely! There are times when one is preferable, and times when the other is. Pattern matching is especially nice when you need to include conditionals and types: vehicle match {
case car: Car if (car.passengers > 2) => addToHovLane(car)
case truck: Truck => reject("No trucks allowed")
case _ => totalTraffic += 1
}
There's a lot of casting going on there, and it's all handled in the pattern match. Converting this to if/else statements would require a lot of type tests and intermediate variables. Personally, I think that would make things harder to read.That said, sometimes (often!) the more compact code is, the harder it is to read. I think it's always worth taking a few extra characters to improver readability. So I only use pattern matching with types and discards when I think it makes the code more readable and more flexible (e.g. easier to refactor, improves separation of concerns). BTW, thanks for pushing back on this. I'm working on the 4th edition of Head First C# (O'Reilly), and C# added syntax very similar to this (borrowed from F#). Writing this reply gave me the opportunity to start thinking through how I want to teach it. |