Kelvin Kelvin - 2 months ago 8x
Java Question

How to specify target type for collection literals?

I'm trying to use a target type to specify a collection literal's type:

val java.util.HashMap<String,String> map = #{
'a' -> 'b'

But I get: error: incompatible types: Set<Object> cannot be converted to HashMap<String,String>
final HashMap<String, String> map = Collections.<Object>unmodifiableSet(CollectionLiterals.<Object>newHashSet(_mappedTo, _mappedTo_1, _mappedTo_2, _mappedTo_3));

Note that this is a java compilation error, not an Xtend one. For some reason Xtend is trying to generate a
even though the target type is a

However, if I change the target type to
, it generates a map as expected.

The Xtend docs say

In addition xtend supports collection literals to create immutable collections and arrays, depending on the target type

so I thought I could control the type of unmodifiable map I get back.

Xtend version: 2.9.0


You cannot do that way you want - implicit conversion won't change the type of map literal for you (bug you are getting is compiler artifact - it gets confused between set of pairs and map literals). What you can do instead is

val map = Maps.newHashMap(#{
        'a' -> 'b'

which is probably even less typing ;) Maps is from, which you will get together with xtend in dependencies.