Search code examples
javakotlininheritanceinterfaceenforcement

Is it possible to enforce two classes to implement the same field names but of differing type at compile time?


Let's say there's two parallel classes:

class A(
        val stringField: String,
        val intField: Int,
        val floatField: Float
)

class B(
        val stringField: Boolean,
        val intField: Boolean,
        val floatField: Boolean
)

Notice that both classes have the same field names but their types differ.

I was wondering whether it could be possible to enforce in some way at compile time so that it wouldn't compile when class A has a field name that class B doesn't have.

At runtime I could probably use some reflection to enforce this but I'm genuinely curious about whether it's possible at compile time and would also prefer not having to resort to reflection for this.

EDIT 1: I do see now that generics are probably part of the solution here, but in the real case scenario class A has a lot of fields of different types and in class B all fields are always of type Boolean. Ideally I don't have to add a generic for every different field type used in class A

EDIT 2: Further details about the use case at hand:

I need to transform a Full object into a Partial one based on some Configuration (the fields for which the configuration is false should end up being null in the Partial object). These three classes are showing a close resemblences, that's why I wanted to enforce a contract over them (so they don't get out of sync over time).

class Full(
        val stringField: String,
        val intField: Int,
        val floatField: Float,
        ...
)

class Partial(
        val stringField: String?,
        val intField: Int?,
        val floatField: Float?,
        ...
)

class Configuration(
        val stringField: Boolean,
        val intField: Boolean,
        val floatField: Boolean,
        ...
)

Solution

  • It isn't a compile-time check but you can always write a test that enforces this constraint.

    I, for example, wrote a test that finds all functions decorated with my DSL annotation and verifies that all of them are described in our doc(yes! testing the documentation!).

    You can use reflections library which makes it more fun to work with reflection(kotlin-reflect is already good but still...).