4

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?

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I do get a warning: "private data class constructor is exposed via the 'generated' copy method".
Basically, the warning means that, while usually you want a private constructor to restrict its calls and have the control over where it's called, here, the constructor is also implicitly called in the generated copy implementation. You can make the constructor non-private (protected constructor will go, though it may look meaningless) or suppress the warning with @Suppress("DataClassPrivateConstructor") (that's what IntelliJ suppress quick fix inserts).
Yeah the class will be closed by default anyway. Thanks again for the solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.