user13520662
user13520662

Reputation:

Mutable list with different types of data

I have a mutable list which can have items of different data classes. For example, val items: List<ItemData>, and ItemData is a class of

sealed class ItemData {
    data class itemOne(
            val valueOne
    ) : ItemData()

    data class itemTwo(
            val valueTwo
    ) : ItemData()

    data class itemThree(
            val valueThree
    ) : ItemData()
}

Say I want to take the list and whenever item is of certain type, update some value there. My question is, how to make sure that item is exactly the type I need? I tried with item as ItemData.itemTwo but I get class cast exception, since in my list are items of other types, too.

Upvotes: 1

Views: 531

Answers (2)

axwcode
axwcode

Reputation: 7824

The trick is to use the keyword is. It lets you check the instance of the element is of a type. Essentially, you say is itemData of type ItemData.ItemOne

mixedList.forEach { itemData ->
    when (itemData) {
         is ItemData.ItemOne -> // This is ItemOne
         is ItemData.ItemTwo -> // This is ItemTwo
         is ItemData.ItemThree -> // This is ItemThree
    }
}

Upvotes: 0

theThapa
theThapa

Reputation: 631

@aswi We can achieve this by using when with is check, please refer to below code sample:

// ItemData class
sealed class ItemData {
    data class ItemOne(
        val valueOne: Int
    ) : ItemData()

    data class ItemTwo(
        val valueTwo: String
    ) : ItemData()

    data class ItemThree(
        val valueThree: Boolean
    ) : ItemData()
}

This is how the type check works:

@JvmStatic
fun main(args: Array<String>) {

    val mixedList = listOf(
        ItemData.ItemOne(1), ItemData.ItemTwo("One"), ItemData.ItemThree(true)
    )
    mixedList.forEach { itemData ->
        when (itemData) {
             is ItemData.ItemOne -> println("This is ItemOne")
             is ItemData.ItemTwo -> println("This is ItemTwo")
             is ItemData.ItemThree -> println("This is ItemThree")
        }
    }
 }

Upvotes: 1

Related Questions