Search code examples
kotlindata-class

How to increment an Integer field in a Kotlin Data Class


I have a Data Class:

data class MyAlarmStatus(
    val notifyTimes: Int
)

What I would like to do invoke this data class whilst incrementing the Integer field simultaneously:

val myAlarmStatus = MyAlarmStatus(
                notifyTimes++
            )

However, this doesn't compile because of an unresolved reference on this field. Anybody have an idea how to achieve this?


Solution

  • If you're wanting to be able to create an incremented version of an existing instance of the class, you can give it an operator function:

    data class MyAlarmStatus(
        val notifyTimes: Int
    ) {
        operator fun inc() = MyAlarmStatus(notifyTimes + 1)
    }
    
    //Usage:
    var alarmStatus = MyAlarmStatus(1)
    alarmStatus++ //Instantiates new instance with incremented property value and assigns it to the var
    

    If you're wanting to increment some previously used value when instantiating one of these, you would need to keep it as a separate property.

    var lastNotifyTimes = 0
    
    var alarmStatus = MyAlarmStatus(++lastNotifyTimes)