1

I have a data class:

data class Person (
    val login: String,
    val password: String
)

Sometimes I need to instantiate it with my custom data, but sometimes I need to initialize my user by another class instance:

val authPerson = api.getAuthPerson()  // AuthPerson class has the same fields
val user = User(authPerson)

I wrote secondary constructor, but it doesn't work:

data class User (
    val login: String,
    val password: String
) {
    constructor(authPerson: AuthPerson) {
        login = authPerson.login;
        password = authPerson.password
    }
}

Can anybody advise me correct decision please?

2 Answers 2

4

Or if you don't want to use a factory, you can do:

data class User (
    val login: String,
    val password: String
) {
    constructor(anotherUser: User): this(anotherUser.login, anotherUser.password)
}

Secondary Constructors must call their primary constructor.

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

Comments

2

You can create a factory method:

data class User(
    val login: String,
    val password: String
) {
    companion object {
        fun fromPerson(person: Person) = User(person.login, person.password)
    }
}
...
val user = User.fromPerson(person)

or create an extension function:

fun Person.toUser() = User(login, password)
...
val user = person.toUser()

Comments

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.