Why are cast types and cast types considered bad style in Scala?

In the book "Programming" in Scala, 2nd ed., Authors write that "writing test types and throws is pretty verbose in Scala. This is intentional because it is not encouraged. Usually you better use pattern matching with a typed template." Elsewhere, they reiterate that using these designs is a "bad style."

I totally agree that the syntax for matching a Scala pattern is much nicer, but isn't it syntactic sugar for checking types and types? Or am I missing something?

+6
source share
1 answer

It is sugar, but it is very healthy sugar. You may run into real cast problems

  • Do not check isInstanceOf before calling asInstanceOf
  • Forgetting that generics don't know their argument type with isInstanceOf
  • Does not apply to all cases for the transferred type.

Matching templates handles all this correctly for you: you only get an instance, if it really is, it warns about generics and warns if you have an incomplete match. Thus, in cases where tests and type checks are error prone, pattern matching is reliable and contributes to good design.

+14
source

All Articles