Search code examples
kotlindata-class

Kotlin data class with different backing field type


I have a simple class used for JSON serialization. For this purpose, the external interface uses Strings, but the internal representation is different.

public class TheClass {

    private final ComplexInfo info;

    public TheClass(String info) {
        this.info = new ComplexInfo(info);
    }

    public String getInfo() {
        return this.info.getAsString();
    }

    // ...more stuff which uses the ComplexInfo...
}

I have this working in Kotlin (not sure if there's a better way). But the non-val/var constructor prevents me from using data.

/*data*/ class TheClass(info: String) {

    private val _info = ComplexInfo(info)

    val info: String
        get() = _info.getAsString()


    // ...more stuff which uses the ComplexInfo...
}

How do I get this working as a data class?


Solution

  • You can use a combination of a private ComplexInfo property declared in the primary constructor and a secondary constructor that accepts a String.

    Optionally, make the primary constructor private.

    Example:

    data class TheClass private constructor(private val complexInfo: ComplexInfo) {
    
        constructor(infoString: String) : this(ComplexInfo(infoString))
    
        val info: String get() = complexInfo.getAsString()
    }
    

    Note that it's the complexInfo property that is used in the data class generated members implementations.