Why can't we override `||` and `&&`?

筅森魡賤 提交于 2019-12-01 15:38:15
Linuxios

Unlike some other operators on objects, who's behavior logically can depend on class, the boolean operators are part of the language. When you have an operator like, say, ==, it is logical to say that the behavior of this operator depends on the type of object. A string should check character by character, a Hash key-value tuple by key-value tuple, etc. However, the behavior of && and || are based on the language's definition of true and false, not anything object specific. If the language allowed you to override these operators, there could be no consistent boolean model, and these operators would become completely useless.

Additionally, there is a performance consideration too. Because && and || are short circut operators, which means that if the first argument to, say, &&, evaluates to false, the second one is never even evaluated. With ||, if the first evaluates to true, the second is never evaluated. This behavior would not be possible if you could override these operators, as in Ruby operators are overloaded as methods. And all parameters must be evaluated, by definition, before the method is called. So, the performance boost, and programming convenience of a short circuit operator is lost.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!