Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are type checks and type casts considered poor style in Scala?

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?

like image 841
mitchus Avatar asked Dec 08 '12 08:12

mitchus


1 Answers

It is sugar, but it's very helpful sugar. You can get into real trouble with type casts by

  • Not checking isInstanceOf before calling asInstanceOf
  • Forgetting that generics don't know their argument type with isInstanceOf
  • Not covering all cases for the type being passed

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.

like image 187
Rex Kerr Avatar answered Nov 11 '22 10:11

Rex Kerr