0

Below is a class that I'm currently working on

@Parcelize
class Time(var hour:Int, var minute:Int):Comparable<Time>,Parcelable

I want to add a setter to member variables hour and minute so that they would stay in time format. And the class has to be passed through intent, so it implements Parcelable. But it says that a Parcelable class should have a primary constructor so I'm having problem with adding setters. Can anyone please tell me why and a solution? Thank you.

Inyoung Kim 김인영
  • 1,434
  • 1
  • 17
  • 38

1 Answers1

2

Kotlin's properties are already shipped with getters and setters. Every time you say time.hour = 5 or val currentTime = time.hour - corresponding setter or getter is invoked.

The problem here is not with constructor, but with CREATOR that parcelable requires.

The complete example would look like this:

class Time(var hour: Int, var minute: Int) : Comparable<Time>, Parcelable {

    override fun writeToParcel(dest: Parcel?, flags: Int) {
        dest!!.writeInt(hour)
        dest.writeInt(minute)
    }

    override fun describeContents(): Int = 0

    override fun compareTo(other: Time): Int {
        // your comparsion logic
    }

    companion object CREATOR : Parcelable.Creator<Time> {
        override fun createFromParcel(parcel: Parcel): Time {
            return Time(parcel.readInt(), parcel.readInt())
        }

        override fun newArray(size: Int): Array<Time?> {
            return arrayOfNulls(size)
        }
    }
}
nyarian
  • 4,085
  • 1
  • 19
  • 51