Lauri Lavanti
Lauri Lavanti

Reputation: 63

Instantiating all classes that extend trait in Scala

So I'm building a library, and the problem I have is as follows:

I have a trait, such as

package my.library
trait Animal {
  def randomFunctions
}

What I need to know is all the classes the consumer code has, that extend/implement said trait, such as

package code.consumer
case class Cat extends Animal
case class Dog extends Animal

So in summary: inside my library (which has the trait) I need to find out all classes (in consumer code) that extend/implement the trait.

Upvotes: 1

Views: 1596

Answers (2)

Lauri Lavanti
Lauri Lavanti

Reputation: 63

I finally solved this by using reflections (https://github.com/ronmamo/reflections) with the following little snippet:

val reflection = new Reflections()
reflection.getSubTypesOf(classOf[Animal])

Upvotes: 5

Andreas Neumann
Andreas Neumann

Reputation: 10904

An option would be to use a sealed trait. This forces all implementations of the trait to reside in the same file as the trait was defined.

This would break your separation of consumer and library code but you would be sure to get all implementations.

The only other option I can think of is to use an IDE, like IntelliJ which has an option to find all implementation based on given trait.

Upvotes: 0

Related Questions