Usage of Kotlin typealias for Map.Entry in Map

Viewed 523

In Kotlin, it's possible to define typealias for classes, hence, also for Map<K,V>. Let's say, that I have the following:

typealias MyMap = Map<String, String>

But, what if I'd like to name the map entry as well, like this:

typealias MyEntry = Map.Entry<String, String>
typealias MyMap = Map<MyEntry> // error

However, Kotlin does not accept this, since Map<K,V> requires a type for the key and the value. Is such a thing as shown above possible?

2 Answers

No. This has nothing to do with typealias, rather how to declare generic types.

Map interface requires two type parameters and you must provide both otherwise you get the error, If you want to use a Map which is parameterized over its entry rather than Key, Value then you can define your own Map Type.

In the above case when you do Map<MyEntry>, you want the language to take the single type parameter (MyEntry) that you provide and extract its two components(String and String) and then use those two components as two different type parameters for the Map. Sorry you are asking too much.

MyEntry is a single type and it can only be used as such. Following is an example of that

typealias MyMap = Map<MyEntry, String>

The real answer is mightyWOZ's, but maybe this tip helps as well:

You can still use generics in typealiases to forward one of the arguments:

typealias StringMap<T> = Map<String, T>
Related