1

Let's imagine that we have data class with two properties and we need secondary constructor for some reasons. Problem is that i need recalculate each argument in primary constructor call instead of using some cached value of raw.split("_"):

data class Id(
    val arg1: String,
    val arg2: String
) {
    constructor(raw: String) : this(raw.split("_")[0], raw.split("_")[1])
}

I can do this in Java but how I can do this in Kotlin?

1 Answer 1

2

You can do it this way:

data class Id(
    val arg1: String,
    val arg2: String
) {

    private constructor(splitted: List<String>) : this(splitted[0], splitted[1])

    constructor(raw: String) : this(raw.split("_"))
}

It's a good and idiomatic way to solve your problem. Since all secondary constructors must delegate to primary constructor (data class always has it), you can't do what you want in constructor body. In Java it works because there are no primary constructors and no data classes at language level - in Kotlin you can do it like in Java too if you remove data modifier and move properties outside of constructor, but it's a really bad way.

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

1 Comment

I know about primary constructor and data class restrictions in Kotlin. I thought that Kotlin have some syntax sugar for code which you show above because it's smells a little - calculation not encapsulated in constructor method(because in-between constructor created => class scope clogged). But anyway its solved the problem! Thanks a lot!

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.