ZbyszekKr
ZbyszekKr

Reputation: 512

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:

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.

Upvotes: 1

Views: 72

Answers (1)

sebszyller
sebszyller

Reputation: 853

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
}

Upvotes: 2

Related Questions