Java 8 Lambda 以函数<String, Object> 作为参数
Java 8 Lambda with Function<String, Object> as argument
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 合成为函数?
当您为泛型类型创建 new CSVFile()
时,它将成为原始类型。您不得使用原始类型。将其创建为原始类型也会将其所有方法更改为原始类型,因此 withColumnMapping(String, String, Function<String, Object>)
变为 withColumnMapping(String, String, Function)
并且无法推断出您的 lambda 参数的类型。要解决您的问题,请在调用构造函数时指定正确的通用参数。
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 合成为函数?
当您为泛型类型创建 new CSVFile()
时,它将成为原始类型。您不得使用原始类型。将其创建为原始类型也会将其所有方法更改为原始类型,因此 withColumnMapping(String, String, Function<String, Object>)
变为 withColumnMapping(String, String, Function)
并且无法推断出您的 lambda 参数的类型。要解决您的问题,请在调用构造函数时指定正确的通用参数。