Scala DSL: method chaining with parameterless methods

给你一囗甜甜゛ 提交于 2019-12-09 12:41:37

问题


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.


回答1:


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




回答2:


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.




回答3:


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?



来源:https://stackoverflow.com/questions/9173848/scala-dsl-method-chaining-with-parameterless-methods

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!