0

Is there a way I can test if the class of a value is one that is an inner class? So say I have the follwing:

trait A {
}

class Outer {
    class Inner extends A {
    }

    val a: A = new Inner
}

val outer = new Outer

Then can I test if the value 'a' is of type Inner? So can I do something like below (which won't compile of course):

outer.a match {
    case _: Outer.Inner =>
}
user79074
  • 4,937
  • 5
  • 29
  • 57

1 Answers1

1

The dot notation . can be used only when the identifier on the left refers to a value, otherwise we should use type projection hash # notation like so

case _: Outer#Inner =>

Contrast the following syntax

val outer = new Outer
(outer.a: Any) match {
  case _: outer.Inner => "<value>.<type>"
  case _: Outer#Inner => "<type>#<type>"
}

The following subtyping relationships of path-dependent types are worth keeping in mind

import shapeless.=:!=

class Outer {
  class Inner
}

val outerX: Outer = new Outer
val outerY: Outer = new Outer
val innerX: outerX.Inner = new outerX.Inner
val innerY: outerY.Inner = new outerY.Inner
// val innerZ: Outer#Inner = new Outer#Inner // error: Outer is not a legal prefix for a constructor
val innerZ: Outer#Inner = new outerX.Inner

implicitly[Outer#Inner =:= Outer#Inner]
implicitly[outerX.Inner <:< Outer#Inner]
implicitly[outerY.Inner <:< Outer#Inner]
implicitly[outerX.Inner =:!= outerY.Inner]
// implicitly[innerZ.Inner =:= outerX.Inner] // error: type Inner is not a member of Outer#Inner
Mario Galic
  • 47,285
  • 6
  • 56
  • 98