Throwing exceptions in Scala, what is the “official rule”

前端 未结 2 914
时光说笑
时光说笑 2020-12-02 10:23

I\'m following the Scala course on Coursera. I\'ve started to read the Scala book of Odersky as well.

What I often hear is that it\'s not a good idea to throw except

2条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-02 11:12

    So this is one of those places where Scala specifically trades off functional purity for ease-of-transition-from/interoperability-with legacy languages and environments, specifically Java. Functional purity is broken by exceptions, as they break referential integrity and make it impossible to reason equationally. (Of course, non-terminating recursions do the same, but few languages are willing to enforce the restrictions that would make those impossible.) To keep functional purity, you use Option/Maybe/Either/Try/Validation, all of which encode success or failure as a referentially-transparent type, and use the various higher-order functions they provide or the underlying languages special monad syntax to make things clearer. Or, in Scala, you can simply decide to ditch functional purity, knowing that it might make things easier in the short term but more difficult in the long. This is similar to using "null" in Scala, or mutable collections, or local "var"s. Mildly shameful, and don't do to much of it, but everyone's under deadline.

提交回复
热议问题