Referring to the type of an inner class in Scala

前端 未结 3 2071
攒了一身酷
攒了一身酷 2020-12-01 21:13

The following code tries to mimic Polymorphic Embedding of DSLs: rather than giving the behavior in Inner, it is encoded in the useInner method of

相关标签:
3条回答
  • 2020-12-01 21:55

    The problem is as you describe, that useInner is expecting an Inner of a specific Outer instance. Since enclosing returns a generic Outer, there is really no way to tie both together that I know of.

    You can force it, however:

    def toBoolean(x: Outer#Inner): Boolean = {
      val outer = x.enclosing
      outer.useInner(x.asInstanceOf[outer.Inner])
    }
    
    0 讨论(0)
  • 2020-12-01 22:01

    You can also define your member like this:

    def useInner(x:Outer#Inner) : Boolean
    

    Or you can write like this:

    abstract class Outer {
        class InnerImpl {
            def enclosing = Outer.this
        }
        final type Inner = Outer#InnerImpl
        def useInner(x:Inner) : Boolean
    }
    
    0 讨论(0)
  • 2020-12-01 22:03

    I suppose the type Inner is like the type this.Inner. Outer#Inner is independent of the outer instance (not a path-dependent type).

    abstract class Outer {
      sealed class Inner {
        def enclosing = Outer.this
      }
      def useInner(x:Outer#Inner) : Boolean
    }
    
    def toBoolean(x:Outer#Inner) : Boolean = x.enclosing.useInner(x)
    
    0 讨论(0)
提交回复
热议问题