Kotlin best practice of data structure with inheritance and required parameters?

Viewed 49

Is there a possibility in Kotlin to construct an Object that allows sub-objects and where you are only allowed to construct the sub-objects and must pass obligatory parameters defined in the parent object and obligatory parameters defined in each sub-object?

I was thinking in a call like this:

val obj1 = TransferObject.TransferObject_ONE(system = "sys3", obligatoryString = "myString", amount = 12)

With a code like this:

enum class SupportedTypes {
        ONE, TWO
    }

sealed class TransferObject(
        val type: SupportedTypes,
        val system: String = "sys1",
        val amount: String,
        val awaitReceipt: Boolean = true
    ) {
        data class TransferObject_ONE(
            val obligatoryString: String
        ) : TransferObject(SupportedTypes.ONE)

        data class TransferObject_TWO(
            val obligatoryInt: Int
        ) : TransferObject(SupportedTypes.TWO)
    }

But of course this won't work, do you have a recommendation, would maybe a factory be the ideal solution for this case?

0 Answers
Related