Scala DSL:方法链与无参数方法 [英] Scala DSL: method chaining with parameterless methods

查看:47
本文介绍了Scala DSL:方法链与无参数方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个小型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
)

定义此dsl的代码大致如下:

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.

推荐答案

好的,我认为,我找到了可接受的解决方案。 ..我现在已经实现了这种可能的语法

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

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

,我几乎可以写我想要的dsl。通常,;如果无参数,则在calc之后需要。这里的窍门是接受DSL对象本身(此处是下一行的 |)。将此参数设为隐式还允许 calc 作为此代码中的最后一条语句。
很好,看起来绝对不可能以我想要的方式拥有它,但这也可以

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

这篇关于Scala DSL:方法链与无参数方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆