我想有这样的代码:
package test
object Outer {
import Outer._
implicit class OuterInt(val self: Int) extends AnyVal {
def *(that: test.Outer.Inner) = that * self
def +(that: Outer.Inner) = that + self
def -(that: Inner) = that - self
}
}
class Outer {
class Widget(w: Widget) extends Inner(w) {}
class Inner(private[Outer] val widget: Widget) {
def *(that: Int) = this
def +(that: Int) = this
def -(that: Int) = this
}
}
我正在编写一个DSL,我希望能够编写诸如
val i = new Inner(...)
2 * i
我相信隐式类将允许2*i
在Inner
对象上编译和调用*
方法。 但是,我无法获得编译器要找到的对Inner
的引用。
它们失败并出现以下错误:
type Inner is not a member of object test.Outer (for *)
type Inner is not a member of object test.Outer (for +)
not found: type Inner (for -)
前两条错误消息表明它正在对象(而不是类(中查找类型。 我尝试将隐式类移动到类中,但这给出了一个错误,即隐式类型不能在类中。
我需要做什么来引用Inner
类?
您可以使用#
运算符:Outer#Inner
。
def * (that: Outer#Inner) = that * self