简体   繁体   English

Scala DSL,对象和中缀表示法

[英]Scala DSL, Object and infix notation

in Scala, if I want to implement a DSL, is there a way to do the following: 在Scala中,如果我想实现DSL,有没有办法执行以下操作:

I have an Object called "Draw" which contains the function def draw(d:Drawable) 我有一个名为“Draw”的对象,其中包含def draw(d:Drawable)函数def draw(d:Drawable)

how can I make it so that I can import the Object and call it outside the object like: 我怎样才能使它能够导入Object并在对象外部调用它,如:

draw ball

if ball extends the Drawable trait? 如果球扩展了Drawable特征? 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. 问题是我想在一种中缀符号中使用draw,但我不想通过表示它实现类/对象来限定函数draw。

You can't do it. 你不能这样做。 Aside from four prefix operators, in any operator notation the first token represents the object. 除了四个前缀运算符之外,在任何运算符表示法中,第一个标记表示对象。

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: 在那里我不得不使用绘画(球)而不是绘球,如你所愿:


Welcome to Scala version 2.8.0.RC2 (Java HotSpot(TM) 64-Bit Server VM, Java 1.6.0_20).

scala> trait Drawable{def doSomething} defined trait Drawable

scala> object Draw {
def draw(d:Drawable) = d.doSomething } defined module Draw

scala> val ball = new Drawable{def doSomething = println("doing ball")} ball: java.lang.Object with Drawable = $anon$1@3a4ba4d6

scala> import Draw._ import Draw._

scala> draw ball :11: error: missing arguments for method draw in object Draw; follow this method with `_' if you want to treat it as a partially applied function draw ball ^

scala> draw(ball) doing ball

However by defining Draw as a class, it did work: 但是,通过将Draw定义为类,它确实有效:


scala> trait Drawable{def doSomething: Unit}
defined trait Drawable

scala> class Draw {
def draw(d:Drawable) = d.doSomething } defined class Draw

scala>

scala> val ball = new Drawable{def doSomething = println("doing ball")} ball: java.lang.Object with Drawable = $anon$1@36a06816

scala> val d = new Draw d: Draw = Draw@7194f467

scala> d draw ball doing ball

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. 我不完全确定为什么这与对象的工作方式不同,可能是一个bug或者也许是指定的行为。 However I didn't have the time to look it up at the moment. 但是我现在没有时间查阅它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM