wrm
wrm

Reputation: 1908

Scala DSL: method chaining with parameterless methods

i am creating a small scala DSL and running into the following problem to which i dont really have a 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 roughly 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: how can i get rid of these parenthesis after calc? is it possible? if so, how? just omitting them in the definition does not help because of compilation errors.

Upvotes: 6

Views: 1303

Answers (3)

Daniel C. Sobral
Daniel C. Sobral

Reputation: 297165

It's not possible to get rid of the parenthesis, but you can replace it. For example:

object it

class Compute {
 def calc(x: it.type):Compute = { ... }

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

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

object method
non-reserved-word

It assumes it means object.method(non-reserved-word). Conversely, whenever it sees something like this:

object method object
method2 object2

It assumes these are two independent statements, as in object.method(object); method2.object, expecting method2 to be a new object, and object2 a method.

These assumptions are part of Scala grammar: it is meant to be this way on purpose.

Upvotes: 4

wrm
wrm

Reputation: 1908

ok, i think, i found an acceptable solution... i now achieved this possible syntax

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

using an object named "|", i am able to write nearly the dsl i wanted. normaly, a ";" is needed after calc if its parameterless. The trick here is to accept the DSL-object itself (here, its the "|" on the next line). making this parameter implicit also allows calc as a last statement in this code. well, looks like it is definitly not possible to have it the way i want, but this is ok too

Upvotes: 4

thoredge
thoredge

Reputation: 12601

First try to remove the parentheses from the definition of calc. Second try to use curly braces around the whole instead of parentheses. Curly braces and parentheses doesn't mean the same and I find that parenthesis works best in single line code (unless using semi-colons). See also What is the formal difference in Scala between braces and parentheses, and when should they be used?

Upvotes: -1

Related Questions