我有一个名为“Draw”的对象,其中包含def draw函数(d:Drawable)
我怎样才能使它能够导入Object并在对象外部调用它,如:
draw ball
如果球扩展了Drawable特征?问题是我想在一种中缀符号中使用draw,但我不想通过表示它实现类/对象来限定函数draw.
解决方法
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 Drawscala> 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
但是,通过将Draw定义为类,它确实有效:
scala> trait Drawable{def doSomething: Unit} defined trait Drawablescala> class Draw {
def draw(d:Drawable) = d.doSomething } defined class Drawscala>
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
我不完全确定为什么这与对象的工作方式不同,可能是一个bug或者也许是指定的行为.但是我现在没有时间查阅它.