Scala DSL, object notation and infix

in Scala, if I want to implement DSL, is there a way to do the following:

I have an object called "Draw" that contains a def draw(d:Drawable) function def draw(d:Drawable)

how can I do this so that I can import the object and call it outside the object, for example:

 draw ball 

if the ball extends the drawable? The problem is that I want to use draw as a musical infix notation, but I do not want to qualify the draw function, denoting its implementation of the class / object.

+6
scala dsl infix-notation
source share
2 answers

I quickly tried, but could well get it to work using the object. There I had to use a draw (ball) instead of a 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, defining Draw as a class, it really worked:

 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 am not quite sure why this does not work the same as with the object, there may be an error or, possibly, the specified behavior. However, I did not have time to watch it at the moment.

+3
source share

You cannot do this. In addition to the four prefix operators, in any operator designation, the first token represents an object.

+6
source share

All Articles