Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring List of multiple types in Kotlin

Tags:

android

kotlin

I'm trying to have a mutable list which contains multiple types, says my data type and String. I have my data class MyObject

data class MyObject(val date: Date?, val description: String?)

So I expect something like list below:

var myList = mutableListOf<MyObject, String>()

Is there any way to archive it in Kotlin?

like image 759
Ti3t Avatar asked Jun 14 '18 06:06

Ti3t


People also ask

How do I add multiple items to a list in Kotlin?

If you need to add multiple elements to a mutable list, you can use the addAll() function. That's all about adding elements to a list in Kotlin.

How do I declare a list on Kotlin?

Inside main() , create a variable called numbers of type List<Int> because this will contain a read-only list of integers. Create a new List using the Kotlin standard library function listOf() , and pass in the elements of the list as arguments separated by commas.

What is the difference between Array and list of in Kotlin?

So, these are some of the differences between a List and an Array. If you have a fixed size data then arrays can be used. While if the size of the data can vary, then mutable lists can be used. Do share this tutorial with your fellow developers to spread the knowledge.


2 Answers

You can create a list that has the first common supertype of your two types as its type parameter, which in this case is Any:

val myList = mutableListOf<Any>()
myList.add("string")
myList.add(MyObject(null, null))

Of course this way you'll "lose" the type of the items that are in the list, and every time you get a list item you'll only know it by the type Any:

val item: Any = myList.get(0)

At this point you can make type checks to see what the type of the item is:

if (item is MyObject) {
    println(item.description)
}
like image 133
zsmb13 Avatar answered Sep 19 '22 02:09

zsmb13


In this specific case where the types are known and limited to two elements, I would use Pair:

var myList = mutableListOf<Pair<MyObject,String>>()

Full code snippet below:

import java.util.Date

data class MyObject(val date: Date?, val description: String?)

var myList = mutableListOf<Pair<MyObject,String>>()

   fun main(args: Array<String>) {
   val first = MyObject(Date(), "time1")
   val second = "info1"
   myList.add(Pair(first, second))
   println(myList[0])
}
like image 42
Krishnamoorthy Karthikeyan Avatar answered Sep 20 '22 02:09

Krishnamoorthy Karthikeyan