3 ms·
The same applies to abstract class / trait with a default implementation. The compiler would also silently accept if after adding a new behavior you forget to u
by pkolaczk 6y ago
The same applies to abstract class / trait with a default implementation. The compiler would also silently accept if after adding a new behavior you forget to update the implementations which need a customized version of that behavior.
Also in the case described in the post, somehow the compiler didn't optimize the polymorphic case despite being able to see all implementations. I guess separate compilation of units makes the closed-world appear like an open-world to the compiler.
- lmm 6y ago> The same applies to abstract class / trait with a default implementation. If you deliberately choose to give a default implementation, yes. But you have the option of not giving a default implementation, forcing a compilation error if someone adds a new case and doesn't implement that behaviour. There's no way to achieve the same thing with a switch; if the switch is "closed" then in some languages a missing case is a warning or error, but I've never seen a language where an "open" switch won't be silently accepted and fail at runtime.
- pkolaczk 6y agoBut then you should compare a trait with no default method to a switch with no default case. And a switch with no default case would be reported as an error if some cases are not covered. Also a switch with no default case is still open to extension. But the extensibility happens in a different dimension, as described in the article - the analogue of adding more implementations of an interface is adding more switches, not adding more case clauses. That's why a switch is not a replacement for interfaces.
- lmm 6y ago> And a switch with no default case would be reported as an error if some cases are not covered. In what language? It's not an error in Scala, which is what the post is talking about.
- pkolaczk 6y agoIn Scala or OCaml you get a compile-time warning + runtime error. In Java 14, Kotlin and Rust there is a compile-time error if switch/match expression is non-exhaustive.
- lmm 6y agoYou don't get a compile-time warning in Scala, only a runtime error. https://scastie.scala-lang.org/6fGnDSzDSdmI4USN5k9OTA https://scastie.scala-lang.org/6fGnDSzDSdmI4USN5k9OTA