ZbyszekKr ZbyszekKr - 3 months ago 11
Scala Question

List of inner classes/objects during compilation

This is the simplified code of a class(object) I'm working on:

object T {
val default = A
val options = List(A,B,C)

sealed trait T
object A extends T {
override def toString = "A"
}
object B extends T {
override def toString = "B"
}
object C extends T {
override def toString = "C"
}
}


This hierarchy maps directly to GUI element which requires a
options = List(A,B,C)
to build.

Problem with current approach:


  • Every time I add an extra object I have to change the
    option
    manually. This isn't too much work however the code isn't too elegant this way.



My question is:

Can I generate a list of inner objects during compile time? I wouldn't like to do this during runtime, it would be an overkill.

Answer

To add to @Samar's comment, to make it clear. The following is what you need:

import scala.reflect.runtime.universe._

case object K {
  val default = A
  val options = getObjects[this.type]

  sealed trait T

  object A extends T {
    override def toString = "A"
  }

  object B extends T {
    override def toString = "B"
  }

  object C extends T {
    override def toString = "C"
  }

  def getObjects[T: TypeTag] = typeOf[T].members.collect {
    case m: ModuleSymbol if m.isModule => m
  }.toList
}
Comments