4

Given this question and SI-7046, this isn't at all what I expected.

scalac test.scala && scala Test in Scala 2.11.6 on the following prints an empty Set():

trait Foo
case class Bar() extends Foo
case class Baz() extends Foo

object Test {
  def main(args: Array[String]) {
    import scala.reflect.runtime.universe._
    println( typeOf[Foo].typeSymbol.asClass.knownDirectSubclasses )
  }
}

However, if I change trait Foo to sealed trait Foo, it prints Set(class Bar, class Baz) as expected.

What's going on here?

Community
  • 1
  • 1
helgridly
  • 133
  • 8
  • did you try actually using/referencing Bar and Baz? The JVM dynamically loads classes using a classloader (duh). It might have different loading rules for seemingly unrelated classes that just extend something but be more exhaustive on sealed traits. – Daniel Langdon Dec 03 '15 at 18:21
  • Good question! I checked and adding a declaration + println for Baz() and Bar() doesn't make any difference. – helgridly Dec 03 '15 at 20:11

1 Answers1

3

look the doc

/** If this is a sealed class, its known direct subclasses.
 *  Otherwise, the empty set.
 *
 *  @group Class
 */
def knownDirectSubclasses: Set[Symbol]
余杰水
  • 1,404
  • 1
  • 11
  • 14