Scala: metaclass analogy in python?

in scala I need to implement something similar to python metaclasses. in my case, the goal of using metaclasses is usually to create a registry of all subclasses of a particular base class, i.e. mapping from the dictionary representation of the class to a link to the class. in python, it’s very convenient to put the metaclass in the base class, so nothing needs to be done in each subclass. I want to do something like this in scala. is there any way to imitate metaclasses or otherwise do it differently? thank!

+5
source share
2 answers

There is nothing like python metaclasses. The registry you are talking about may be possible with custom class loaders or reflection.

+2
source

If you know the full name of the class, you can load it using the usual Java reflection methods in java.lang.Class, namely Class.forName(String fqClassName). Given the resulting instance Class, instantiating is easy only with a constructor with a null argument, otherwise you will get confused in the messy world of all Java reflection types.

If you need some kind of “discovery”, where unknown classes are at compile time and whose names are not presented as input or program parameters in some way, the approach to loading classes is probably the only answer.

+4
source

All Articles