Minh-Long Luu
Minh-Long Luu

Reputation: 2731

Kotlin: universal data type in HashMap?

I have some Hash Maps of some objects <String, Object>, some goes like this:

val mapA = HashMap<String, A>
val mapB = HashMap<String, B>
val mapC = HashMap<String, C>

I want to create a function that takes any Hash Map to print it out. This is what I mean:

fun printHashMap(hashMap: HashMap<String, (any type here, for example A, B or C)>){
    // print each element of hashmap
}

What I've tried so far:

fun printHashMap(hashMap: HashMap<Any, Any>){
   // print HashMap here
}

But it throws me Type mismatch, <Any, Any> vs <String, A> for example.
Is this possible in Kotlin?

Upvotes: 1

Views: 209

Answers (1)

Gennady
Gennady

Reputation: 372

If you don't need specific print format, you can print hashMap without your own function:

val testMap = HashMap<String, Any>()
testMap["1"] = 1
testMap["2"] = "2"
print(testMap)

Otherwise, you should change your signature of method to

fun printHashMap(map: Map<String, *>)

In functions better to use Interface instead of concrete class. And instead of Any you need to use star-projections. It is the safe way here is to define such a projection of the generic type, that every concrete instantiation of that generic type would be a subtype of that projection.

You can read more about it here and here

Upvotes: 2

Related Questions