Something weird happens with Enum. All other parameters are fine to override but I have null in the Enum on debug while test shows all is ok.
And I got the runtime error if make the parameter non-nullable in class B.
Works with simple classes also (and you actually, don’t need to override, the error happens just with plain Enum).
Are you sure you use the right B and not some other type? Your above code should not even compile, because you didn’t invoke constructor of B in A. Could you provide a full reproducible example?
Also, overriding a property that has a backing field seems like a code smell to me. This way both B and A create their own p1 field, but the one from B is just not used. Maybe you should make B.p1 abstract or make B at all an interface?
As I wrote in addition, you even don’t need to inherit the parameter. (And yes, I didn’t understand, what’s the profit to override the parameters in constructor instead of other methods).
open class Building(
val category: BuildingCategory = BuildingCategory.NONE,
)
open class House : Building(
category = BuildingCategory.HOUSING,
)
@Test
fun buildingCategory() {
val house = House()
assertEquals(BuildingCategory.HOUSING, house.category)
}
-> java.lang.ExceptionInInitializerError
So you suspect the problem may be related to the implementation of your enum, but you still decided to not provide it neither in your question and even after I asked for a reproducible example. What do you expect people to do if they don’t see the code?
And now we have everything we need to determine what’s the problem in your code. You have a circular reference between House and HOUSING. In order to initialize HOUSING we need to initialize House, but to initialize House we need to have HOUSING initialized already.
Honestly, it seems pretty strange that we can create many different instances of House, but HOUSING keeps a very specific instance for itself. Why do you need this buildings property? Why do you need House class and HOUSING enum separately? Maybe you should use sealed classes instead of enums?
I split my Enum to Enum and a map of instances. But it’s also possible to change instances to classes and then create instances (should be a higher resource-consumption way because of multiple usage). Anyway, I need to make copies and creating new instances of them because of specifics of data classes.
Data class must have at least one primary constructor parameter is still looks messy, will see how to make a better workaround.
data classes just create an equalstoString and hashCode functions with the constructor parameters. Hence for a class whose constructors has no parameters, equals would always return true, toString would return the class name, and hashCode would return some constant.
This class doesn’t have any mutable state.
The constuctor takes no parameters, and there are no setters.
All instances are indistiguishable from one another, this is functionally a singleton.