Operator precedence in Scala

ScalaOperator Precedence

Scala Problem Overview


I like Scala's propose of operator precedence but in some rare cases, unmodified rules may be inconvenient, because you have restrictions in naming your methods. Are there ways to define another rules for a class/file, etc. in Scala? If not, would it be resolved in the future?

Scala Solutions


Solution 1 - Scala

Operator precedence is fixed in the Scala Reference - 6.12.3 Infix Operations by the first character in the operator. Listed in increasing order of precedence:

(all letters)
|
^
&
= !
< >
:
+ -
* / %
(all other special characters)

And it's not very probable that it will change. It will probably create more problems than it fixes. If you're used the normal operator precedence changing it for one class will be quite confusing.

Solution 2 - Scala

> Are there ways to define another rules for a class/file, etc. in Scala? If not, would it be resolved in the future?

There is no such ability and there is little likelihood of it being added in the forseeable future.

Solution 3 - Scala

There was a feature request raised in the typelevel fork of the scala compiler, a version of the compiler which 'previews' experimental features. The developers suggested that if somebody were to write a SIP for this, it may be considered for implementation.

But in it's current state, there is no way to override precedence. It's rules are formally defined in the language specification.

Solution 4 - Scala

>unmodified rules may be inconvenient, because you have restrictions in naming your methods

  • you do not have any restrictions in naming your methods. For example, you can define methods +, -, * and etc. for a class.
  • we must also follow de-facto "unmodified rules" (enforced by Scala operator precedence rules) mentioned in previous answer (https://stackoverflow.com/a/2922456) by Thomas Jung - it is common for many if not all programming languages, and abstract algebra; we need not redefine operator precedence for a+b*c.

See Chapter 6 of the book http://www.scala-lang.org/docu/files/ScalaByExample.pdf for "Rational" class example.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJerihoView Question on Stackoverflow
Solution 1 - ScalaThomas JungView Answer on Stackoverflow
Solution 2 - ScalaRandall SchulzView Answer on Stackoverflow
Solution 3 - ScalaLucianoView Answer on Stackoverflow
Solution 4 - ScalaFuad EfendiView Answer on Stackoverflow