0

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

1
  • 1
    A data class must have all stateful properties declared in the primary constructor so you must swap the two constructors. The secondary one can set the price to zero or null if you want to make it nullable. But you don’t need a secondary constructor because you can use default values in the primary constructor. Commented Oct 10, 2021 at 16:22

1 Answer 1

1

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.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.