Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Usage of Kotlin typealias for Map.Entry in Map

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?

like image 618
Robin Trietsch Avatar asked Oct 29 '25 16:10

Robin Trietsch


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>
like image 55
mightyWOZ Avatar answered Oct 31 '25 12:10

mightyWOZ


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>
like image 35
RobCo Avatar answered Oct 31 '25 10:10

RobCo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!