Dmitrii Bundin Dmitrii Bundin - 19 days ago 6
Scala Question

Omiting parenthesis in Scala

I'm running some experiments with implicit classes and came up with the following issue. Here it is:

object Main extends App {
implicit class IntExtractor(str: String){
def extractInt(i: Int): Int = i + str.##
}

implicit class ArrayCreator(i: Int){
def -->(ii: Int): Array[Int] = Array[Int](i, ii)
def createArray(ii: Int): Array[Int] = Array[Int](i, ii)
}

"STR" extractInt 10 createArray 11 //fine
("STR" extractInt 10) --> 11 //fine
"STR" extractInt 10 --> 11 //compile-error
}


DEMO

What's is the reason for not compiling the example with
-->
method? I thought
-->
is a perfectly valid identifier in
Scala
... like any other identifiers.

Answer

The precedence of operators in Scala is dependent on the first symbol/character of its name as described here 1, the order of precedence being

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

That's why "STR" extractInt 10 createArray 11 is parsed as ("STR" extractInt 10) createArray 11 while "STR" extractInt 10 --> 11 is parsed as "STR" extractInt (10 --> 11) which then produces the compile error.