如何从同伴对象引用Scala内部类

时间:2018-08-21 20:33:08

标签: scala implicit companion-object

我想要这样的代码:

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类?

1 个答案:

答案 0 :(得分:2)

您可以使用#运算符:Outer#Inner

def * (that: Outer#Inner) = that * self