dimanche 16 avril 2023

Classes common behavior + immutability in Kotlin

Is there a way to achieve the following but in a more immutable way?

abstract class Abstract {
    abstract val general1: String
    abstract var counter: Int // Don't want to use var here

    fun sumCounter(value: Int) {
        counter += value
    }
}

data class A (
    val a1: String,

    override val general1: String,
    override var counter: Int = 0,
): Abstract()

data class B (
    val b1: String,
    val b2: String,

    override val general1: String,
    override var counter: Int = 1,
): Abstract()

fun <T : Abstract> doSomething(obj: T) {
    //...
    obj.sumCounter(10) // I want: val newObj = obj.sumCounter(10)


    println(obj) // A(a1=a1, general1=general1, counter=10)
                 // B(b1=b1, b2=b2, general1=general1, counter=11)
    //...
}

fun myMain() {
    val a = A("a1", "general1")
    doSomething(a)

    val b = B("b1", "b2", "general1")
    doSomething(b)
}

It could be some Kotlin trick, functional approach, or design pattern to avoid creating the same methods in A and B. But I don't want to use reflections or convert to json and back.

Aucun commentaire:

Enregistrer un commentaire