Lambda Java 8(Oracle JDK)中有趣的编译错误
java -version
java version "1.8.0_45"
Java(TM) SE Runtime Environment (build 1.8.0_45-b14)
Java HotSpot(TM) 64-Bit Server VM (build 25.45-b02, mixed mode)
我有一个方法调用:
new CSVFile()
.of(new FileInputStream("MyFile.csv"))
.withColumnMapping("name", "fullName", s -> s.toUpperCase())
.withColumnMapping("gender", "gender", s -> s.toUpperCase());
这是我试图调用的方法:
public CSVFile withColumnMapping(final String columnName, final String beanPropertyName, final Function<String, Object> columnTransformFunction) {
columnMappings.add(new ColumnMapping(columnName, beanPropertyName, Optional.of(columnTransformFunction)));
return this;
}
我得到的编译错误是:
[ERROR] /Users/sai/fun/reactivecsv/src/test/java/reactivecsv/CSVFileTest.java:[26,50] cannot find symbol
[ERROR] symbol: method toUpperCase()
[ERROR] location: variable s of type java.lang.Object
很奇怪,这个编译
Function<String, Object> upperCaseConversion = String::toUpperCase;
new CSVFile()
.of(new FileInputStream("MyFile.csv"))
.withColumnMapping("name", "fullName", upperCaseConversion)
.withColumnMapping("gender", "gender", upperCaseConversion);
为什么编译器无法将lambda合成为函数?
答案 0 :(得分:8)
为通用类型创建new CSVFile()
时,它将成为原始类型。您不能使用原始类型。将其创建为原始类型也会将其所有方法更改为raw,因此withColumnMapping(String, String, Function<String, Object>)
变为withColumnMapping(String, String, Function)
,并且无法推断出lambda参数的类型。要解决您的问题,请在调用构造函数时指定正确的泛型参数。