ImmutableList.builder() bug?(ImmuableList.Builder()错误?)
问题描述
我刚刚开始学习番石榴,我注意到ImmutableList.builder()有些奇怪。
这不能编译:
List<String> iList = ImmutableList.builder().add("One").add("Two").build();
//Type mismatch: cannot convert from List<Object> to List<String>
这行得通:
List<String> iList = new ImmutableList.Builder<String>().add("One").add("Two").build();
我可以接受使用new ImmutableList.Builder<String>(),但这是ImmutableList.builder()的错误吗?
推荐答案
否,只需提供类型参数
List<String> iList = ImmutableList.<String>builder().add("One").add("Two").build();
这绝不是Guava中的错误,它只是Java语言的一个特性/限制。编译器无法从以前的方法调用或要将结果赋值到的变量的声明中推断build()的返回类型。
Angelika Langerexplains这个
自动类型参数推理。该方法的调用方式与常规方法一样 非泛型方法,即不指定类型 争论。在这种情况下,编译器会自动推断类型 来自调用上下文的参数。
她在Why does the type inference for an instance creation expression fail?
中也给出了类似的例子String s = new ArrayList<>().iterator().next(); // error
和状态
在上面的示例中,发出错误消息是因为新的 -表达式new ArrayList<;>()没有构造函数参数,它既不出现在赋值的右侧,也不显示为 方法调用的参数。相反,它以链条的形式出现 方法调用的。这样的链不是有效的类型推断上下文。
这篇关于ImmuableList.Builder()错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:ImmuableList.Builder()错误?
基础教程推荐
- 修改 void 函数的输入参数,然后读取 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 如何对 Java Hashmap 中的值求和 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
