user2953119
user2953119

Reputation:

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.

Upvotes: 2

Views: 90

Answers (1)

Fabian Schmitthenner
Fabian Schmitthenner

Reputation: 1706

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.

Upvotes: 6

Related Questions