In the book Programming in Scala, 2nd ed., the authors write that "writing type tests and casts is rather verbose in Scala. That’s intentional, because it is not encouraged practice. You are usually better off using a pattern match with a typed pattern." Elsewhere they repeat that using those constructs is "poor style".
I totally agree that the pattern matching syntax of Scala is much nicer, but isn't it basically syntactic sugar for type checks and type casts? Or am I missing something?
It is sugar, but it's very helpful sugar. You can get into real trouble with type casts by
isInstanceOf
before calling asInstanceOf
isInstanceOf
Pattern matching handles all this for you correctly: you only get an instance if there actually is one, it warns on generics, and warns if you have an incomplete match. Thus, where type tests and casts are error-prone, pattern matching is robust and encourages good design.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With