Question

How do I combine two different classes into one list?

I have two classes, the code is below. I need to put them in one list and sort them by the variable "time". Each class has "time" of type string.

data class Event(
    var data: String,
    var time: String,
    var place: String,
    var event: String
)

data class Task(
    var data: String,
    var time: String,
    var name: String,
    var points: List<String>,
    var checkBoxes: List<Boolean>
)

How can I get them from the list later? I need something like this.

val newList = (events + tasks).sortedBy { it.time }
    for (item in newList ) {
        when (item) {
            is Event -> createNewEvent(item)
            is Task -> createNewTask(item)
        }
    }
 2  27  2
1 Jan 1970

Solution

 2

One solution maybe not the best is using a sealed interface or just a plain interface.

fun main() {
    val events = listOf<Event>()
    val tasks = listOf<Task>()
    val newList = (events + tasks).sortedBy { it.time }
    for (item in newList) {
        when (item) {
            is Event -> createNewEvent(item)
            is Task -> createNewTask(item)
        }
    }
}

data class Event(
    var data: String,
    override var time: String,
    var place: String,
    var event: String
) : Timable

data class Task(
    var data: String,
    override var time: String,
    var name: String,
    var points: List<String>,
    var checkBoxes: List<Boolean>,
) : Timable

interface Timable {
    var time: String
}

If those classes are from a library and you have no access to them you can do this:

val newList = (events + tasks).sortedBy {
        when (it) {
            is Task -> {
                it.time
            }

            is Event -> {
                it.time
            }

            else -> {
                throw Exception("")
            }
        }
    }
2024-07-25
Yamin