Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala DSL: method chaining with parameterless methods

Tags:

scala

dsl

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.

like image 820
wrm Avatar asked Feb 07 '12 09:02

wrm


2 Answers

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

like image 181
wrm Avatar answered Oct 12 '22 12:10

wrm


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.

like image 33
Daniel C. Sobral Avatar answered Oct 12 '22 12:10

Daniel C. Sobral