Scala DSL: a chain of methods with parameterless methods

I create a small scala DSL and run the following problem, to which I really have no solution. A small conceptual example of what I want to achieve:

(Compute write "hello" read 'name calc() calc() write "hello" + 'name ) 

The code defining this dsl is something like this:

 Object Compute extends Compute{ ... implicit def str2Message:Message = ... } class Compute{ def write(msg:Message):Compute = ... def read(s:Symbol):Compute = ... def calc():Compute = { ... } } 

Now the question is: how can I get rid of these brackets after calc? Is it possible? if so, how? simply excluding them in the definition does not help due to compilation errors.

+6
source share
3 answers

OK, I think I found an acceptable solution ... now I have reached this possible syntax

  | write "hello" | read 'name | calc | calc | write "hello " + 'name 

using an object named "|", I can write almost the dsl that I need. normaly, a ";" necessary after calc if its without parameters. The trick here is to accept the DSL object itself (here, its "|" on the next line). making this parameter implicit also allows calc as the last statement in this code. well, it seems like this is not possible, as I want, but that too is normal.

+3
source

It is impossible to get rid of the bracket, but you can replace it. For instance:

 object it class Compute { def calc(x: it.type):Compute = { ... } (Compute write "hello" read 'name calc it calc it write "hello" + 'name ) 

To expand the bit, whenever Scala sees something like this:

 object method non-reserved-word 

This is supposed to mean object.method(non-reserved-word) . And vice versa, whenever he sees something like this:

 object method object method2 object2 

It is assumed that these are two independent operators, as in object.method(object); method2.object object.method(object); method2.object , expecting method2 be a new object and object2 be a method.

These assumptions are part of Scala's grammar: it is designed specifically for this.

+3
source

First try removing the parentheses from the calc definition. The second attempt is to use braces around the whole instead of parentheses. Curly brackets and parentheses do not mean the same thing, and I believe that brackets work best in the same line of code (unless you use half-columns). See Also What is the formal difference in Scala between parentheses and parentheses and when should they be used?

-1
source

Source: https://habr.com/ru/post/907831/


All Articles