Troy Daniels
Troy Daniels

Reputation: 3598

How to reference a Scala inner class from the companion object

I want to have code like this:

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
    }
}

I am writing a DSL where I want to be able to write things like

val i = new Inner(...)
2 * i

I believe that the implicit class will allow the 2*i to compile and call the * method on the Inner object. However, I am unable to get the reference to Inner to be found by the compiler.

They fail with these errors:

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 -)

The first two error messages suggest that it is looking in the object, not the class, for the type. I tried moving the implicit class to the class, but that gave an error that an implicit type cannot be inside a class.

What do I need to do to reference the Inner class?

Upvotes: 0

Views: 374

Answers (1)

Brian McCutchon
Brian McCutchon

Reputation: 8584

You can use the # operator: Outer#Inner.

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

Upvotes: 3

Related Questions