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?
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.
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.
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.
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)
}
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])
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With