Java“lambda转换的目标类型必须是接口”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34426794/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 15:38:33  来源:igfitidea点击:

Java "target type of lambda conversion must be an interface"

javaintellij-idealambda

提问by Mocktheduck

I'm trying to use lambdas and streams in java but I'm quite new to it. I got this error in IntelliJ "target type of lambda conversion must be an interface" when I try to make a lambda expression

我正在尝试在 Java 中使用 lambdas 和流,但我对它很陌生。当我尝试创建 lambda 表达式时,我在 IntelliJ 中收到此错误“lambda 转换的目标类型必须是一个接口”

List<Callable<SomeClass>> callList = prgll.stream()
                                          .map(p->(()->{return p.funct();} )) <--- Here I get error
                                          .collect(Collectors.toList());

Am I doing something wrong?

难道我做错了什么?

采纳答案by Louis Wasserman

I suspect it's just Java's type inference not being quite smart enough. Try

我怀疑这只是 Java 的类型推断不够聪明。尝试

 .map(p -> (Callable<SomeClass>) () -> p.funct())

回答by Bohemian

Stream#map()is a typedmethod, so you can explicitly specify the type:

Stream#map()是一种类型化方法,因此您可以显式指定类型:

 .<Callable<SomeClass>>map(p -> () -> p.funct())

or neater, use a method reference:

或者更简洁,使用方法参考:

 .<Callable<SomeClass>>map(p -> p::funct)