vals
vals

Reputation: 53

In Kotlin, how to check List<Any> contains one or another dataclass?

I have two data classes

    data class Card(val code: String?, val caption: String?, val icon: String?)
    data class Currency(val code: String?, val caption: String?, val descr: String?)

which are organized into lists: List<Card> and List<Currency> which I use as parameters when calling a one function. The parameter type is defined as List<Any>. How inside a class or function I can determine the type of data? Is that list of Card or list of Currency?

This is for Android application on Kotlin

class SpinnerAdapter(val context: Context, var name: List<Any>): BaseAdapter() {
    init {
        if (name.contains(Card)) { //is list of Card?

        }
    }
    override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
   ...

Upvotes: 1

Views: 4230

Answers (2)

Appernicus
Appernicus

Reputation: 464

The answer by Amazia works but you could improve it by implementing a sealed class like so:

sealed class PaymentMethod {
    abstract val code: String?
    abstract val caption: String?

    data class Card(override val code: String?, override val caption: String?, val icon: String?) : PaymentMethod
    data class Currency(override val code: String?, override val caption: String?, val descr: String?) : PaymentMethod
}

More information about sealed classes in Kotlin: https://kotlinlang.org/docs/reference/sealed-classes.html

this allows you to do an exhaustive when clause over your List of PaymentMethods like so (No need for else branch):

class SpinnerAdapter(var name: List<PaymentMethod>) {
init {
    when(name.first()){
        is Card -> {
            //  do something
        }

        is Currency -> {
            //  do something
        }
    }
}

You could also use this exhaustive when in a stream if you'd like:

class SpinnerAdapter(var name: List<PaymentMethod>) {
init {
    name.map{ 
        when(name.first()){
            is Card -> {
                //  do something
            }
            is Currency -> {
                //  do something
            }
        }
    }
}

Upvotes: 1

Amazia Gur
Amazia Gur

Reputation: 1712

i think you can use the cool when feature here that kotlin provides. for example:

class SpinnerAdapter(var name: List<Any>) {
init {
    when(name.first()){
        is Card -> {
            //  do something
        }

        is Currency -> {
            //  do something
        }

        else -> // do something
    }
}

}

this solution rely on that the list of any can have either all card or all currency. if list can hold mixed items, you should run a for loop before and let the when block to decide the flow.

Upvotes: 3

Related Questions