Issue
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?
Solution
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)
}
Answered By - zsmb13
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.