Why I can’t connect multiple Scala method calls

I am working on DSL and I am faced with the problem of using methods as infix operators in the chain. I will just try to explain this with some code. I have a Term trait and case Literal and Variable classes extending it. I want to build a list of term instances using some operators.

 case class Expr(val terms: List[Term]) { def +(v: String) = Expr(Literal(v) :: terms) def -->(func: List[String] => List[String]) = terms match { case Literal(v) :: ts => Expr(Variable(v, func) :: ts) case _ => throw new Exception("Can only apply function on literal") } } object foo { def bar(name: String) = Expr(Literal(name) :: Nil) } // some functions val one = ... val all = ... // works foo bar "x" // res1: Expr = Expr(List(Literal(x))) // works not foo bar "x" --> all // error: value --> is not a member of java.lang.String // works (foo bar "x") --> all // res1: Expr = Expr(List(Variable(x,<function1>))) 

I expect this to be equivalent to foo.bar("x").-->(all) , but the interpreter seems to see it as foo.bar("x".-->(all)) .

+7
source share
1 answer

You can find the operator priority here:

Operator Priority in Scala

In accordance with the first answer - has a higher priority than letters. Thus, the expressions of the compiler groups are as follows:

 foo bar ("x" --> all) 

If you replace --> with something with a lower priority (e.g. letters), then it should compile. For example:

 foo bar "x" to all 

You can also select a higher priority operator instead of bar . Something like ~~> will do this because ~ is a special character and has the highest priority:

 foo ~~> "x" --> all 
+14
source

All Articles