简体   繁体   中英

How to created correctly a secondary constructor for kotlin

I was developing an App, where I manage diferents services offer by the users of the App.

So, I would like to create a secondary constructor, where I'm able to add the price to the service. Regarding what I reading on differents forums, the correctly way is to delegate into this() call the atributes of the primary Constructor, and the secondary constructor is in charge of the new atributes as price in my case.

So I try to do something like this:

@kotlinx.serialization.Serializable
data class Service(
    var status: String?,
    var type: String,
) : Serializable {

    //TODO: Crear onstructor secundario para instanciar
    // los service mostrados en el publishFragment.

    constructor(
        status: String,
        type: String,
        price:Int)
            : this(status, type){

    }
}

But I don't know how to set price without implements into the firts construtor.

I guess

In data classes, the primary constructor must set all the values. In your case you can just use a primary constructor with a default value for the price:

data class Service(
    val type: String,
    val status: String? = null,
    val price: Int? = null
)

You can of course add a secondary constructor instead of having default values and it would simply call the primary constructor with the null values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM