Scala DSL、对象和中缀表示法
在 Scala 中,如果我想实现 DSL,有没有办法执行以下操作:
我有一个名为“Draw”的对象,其中包含函数 def draw(d:Drawable)
我该如何制作这样我就可以导入对象并在对象外部调用它,例如:
draw ball
如果球扩展了可绘制特征?问题是我想以一种中缀表示法使用绘制,但我不想通过表示它正在实现类/对象来限定函数绘制。
in Scala, if I want to implement a DSL, is there a way to do the following:
I have an Object called "Draw" which contains the function def draw(d:Drawable)
how can I make it so that I can import the Object and call it outside the object like:
draw ball
if ball extends the Drawable trait? The problem is that I want to use draw in a kind of infix notation, but I dont want to qualify the function draw by denoting it's implementing class/object.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你做不到。除了四个前缀运算符之外,在任何运算符表示法中,第一个标记都表示对象。
You can't do it. Aside from four prefix operators, in any operator notation the first token represents the object.
我很快就尝试了一下,但使用一个对象完全可以使其工作。在那里,我必须使用绘制(球)而不是绘制球,如您所愿:
然而,通过将 Draw 定义为一个类,它确实起作用了:
我不完全确定为什么这与对象的工作方式不同,可能是一个错误,或者可能是指定的行为。不过我现在没有时间去查。
I quickly tried it out, but could quite make it work using an object. There I had to use draw(ball) instead of draw ball, as you wanted:
However by defining Draw as a class, it did work:
I'm not completely sure why this doesn't work the same way with an object, might be a bug or perhaps that's specified behaviour. However I didn't have the time to look it up at the moment.