0

In many scenarios, I don't need a field to be passed in from the primary constructor, for example, a field is assigned after initialization and some steps have been taken; a field directly accesses a global variable (such as static variables, such as other persistent data).

Now I have the compromise solution is to use var and default value in the primary constructor, or override all serialization methods in companion object: Parceler <Model>, both of which have disadvantages.

Why is Kotlin designed like this? Is there any better solution?

Bear Big
  • 93
  • 7

1 Answers1

1

Because that is how serialization works. For example, you have

data class User(val name: String, val id: Int)

val user = User("foo", 1)

and it serialize to JSON (@Parcelize does not serialize to JSON. This is an example.)

{
  "name": "foo",
  "id": 1
}

When it deserializes JSON, it need to create back the object from the JSON above. Without a primary constructor that have all the necessary fields, it cannot create a same object.

If you have a complex object, you can create a separate class for serialization and create a factory method to accept that class.

Or you can implement Parcelable yourself and you can see why you need all the fields in the constructor.

Joshua
  • 5,901
  • 2
  • 32
  • 52