本文介绍了为什么ImmutableMap.builder().build()不能选择正确的类型参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么Map<String, ?> test = ImmutableMap.builder().build();无法编译,但是Map<String, ?> test = ImmutableMap.<String, Object>builder().build();正常工作?

Why does Map<String, ?> test = ImmutableMap.builder().build(); fail to compile, but Map<String, ?> test = ImmutableMap.<String, Object>builder().build(); work fine?

第一个代码段失败,并显示以下信息:

The first code sniplet fails with:

error: incompatible types
  Map<String, ?> test = ImmutableMap.builder().build();
                                                   ^
  required: Map<String,?>
  found:    ImmutableMap<Object,Object>

我相信Guava提交者是为此工作的.

I believe the Guava committers meant for this to work.

推荐答案

这不是Guava中的失败,而是Java解析泛型的方式,这是我们无法控制的. =(

This is not a failure in Guava, but rather in the way Java resolves generics, and it's something we can't control. =(

相信我们:这是我们花费了不少时间的时间.在此问题中,凯文提到我们尝试了不少而不是十五种尝试获取它的方法,这样您就不必显式指定这些类型参数.

Believe us: this is something that we spent a lot of time on. In this issue, Kevin mentions that we attempted no less than fifteen approaches for trying to get it so that you didn't have to explicitly specify these type parameters.

如果您只对ImmutableMap.builder().build()的情况感兴趣,也就是说,在地图中没有任何条目,那么您应该使用ImmutableMap.of().泛型不会有任何有趣的问题:它会起作用.

If you're only interested in the case of ImmutableMap.builder().build(), that is, with no entries in the map...then you should be using ImmutableMap.of(). That won't have any funny issues with generics: it'll just work.

这篇关于为什么ImmutableMap.builder().build()不能选择正确的类型参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-16 12:58