如何从伴随对象引用 Scala 内部 class

How to reference a Scala inner class from the 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

我相信隐式 class 将允许 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 -)

前两条错误消息表明它正在对象中查找类型,而不是 class。我尝试将隐式 class 移动到 class,但这给出了一个错误,即隐式类型不能位于 class.

我需要做什么才能引用 Inner class?

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

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