Home > front end >  How to do same operation on custom objects that share same variables in Kotlin?
How to do same operation on custom objects that share same variables in Kotlin?

Time:09-16

I have a sealed class containing custom data classes. Some of these data classes store the same variable x like:

sealed class Example {
        data class foo1(var timestamp: String?, var model1: Model1?): Example() 
        data class foo2(var timestamp: String?, var model2: Model2?): Example() 
        data class foo3(var model3: Model3?): Example() 
}

Model3 should also contain a timestamp variable.

What I'm trying to do is something like this:

when(foo) {
       is Foo1, is Foo2 -> {
         //run same piece of code
         foo.timestamp = ts
       }
       is Foo3 -> {
         //run diff piece of code
         foo.model3.timestamp = ts
       }
}

But I am having issues with this because I am getting unresolved reference with "timestamp" when doing the above on the first "is" block. It only works when I individually reference each type and run the same block of code for each which looks really ugly with more object types.

Is there a way I can do the above and have it work, or any suggestions on if I should restructure anything with my approach to get this to work?

CodePudding user response:

Give an abstract var to the supertype.

sealed class Example {
   abstract var timestamp: String?
   data class foo1(override var timestamp: String?, var model1: Model1?): Example() 
   data class foo2(override var timestamp: String?, var model2: Model2?): Example() 
   data class foo3(var model3: Model3?): Example() {
      override var timestamp: String?
         get() = model3?.timestamp
         set(value) { model3?.timestamp = value }
   }
}

Then you don't even have to use when:

foo.timestamp = ts

CodePudding user response:

You can create another sealed class with a common variable that inherits from the base sealed class and use this sealed class as a parent for classes with a common variable.

sealed class Example {
        sealed class Timestamp : Example() {
            abstract var timestamp: String?
        }

        data class foo1(override var timestamp: String?, var model1: Model1?): Timestamp() 
        data class foo2(override var timestamp: String?, var model2: Model2?): Timestamp() 
        data class foo3(var model3: Model3?): Example() 
}


when(foo) {
       is Timestamp -> {
         //run same piece of code
         foo.timestamp = ts
       }
       is Foo3 -> {
         //run diff piece of code
       }
}

Both sealed classes can be declared as sealed interfaces in kotlin 1.5

  • Related