Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java generics and type synonyms

I was considering implementing something like interface Dto<K, V> extends Map<K, V> {} but what I really wanted to express is that Dto<K, V> is a type synonym for Map<K, V> {} like you can do in Haskell http://www.haskell.org/haskellwiki/Type_synonym to improve the readability of code.

Is this possible to express in Java or should I use the Map interface directly?

like image 318
dmz73 Avatar asked Sep 29 '22 17:09

dmz73


1 Answers

As far as I know, Java provides no way to define a synonym.

Generics however do provide some of the expressiveness of synonyms. The parameterized type (e.g. the "V"), indicates the type of object.

Map<Sting, Dto> dtoMap = ...

This is clearly a map of Sting->Dto.

The topic of extending a built-in type purely for renaming is considered by some to be an anti-pattern. Although this is a debated topic. See: https://softwareengineering.stackexchange.com/questions/246277/good-or-bad-practice-to-mask-java-collections-with-meaningful-class-names.

like image 74
EJK Avatar answered Oct 03 '22 00:10

EJK