简体   繁体   English

Kotlin lambda / Java SAM互操作型不匹配

[英]Kotlin lambda / Java SAM interop - type mismatch

I have an existing Java interface defined as follows 我有一个现有的Java接口定义如下

public interface MyRetriever extends Function<String, Optional<String>> {}

and want to define a variable holding a Kotlin lambda which conforms to the SAM conversion as per my understanding 并且想根据我的理解定义一个持有Kotlin lambda的变量,该变量符合SAM转换

var a : MyRetriever = { s : String -> Optional.ofNullable(s.toLowerCase()) }

But instead I get a type mismatch error. 但相反,我得到了类型不匹配错误。

Type missmatch.
Required: MyRetriever
Found: (String) -> Optional<String> 

The lambda actually matches the Java function definition, what am I missing here? lambda实际上匹配Java函数定义,我在这里缺少什么?

When doing a SAM conversion, you need to explicitly provide a type: 进行SAM转换时,您需要明确提供类型:

var a = MyRetriever { s : String -> Optional.ofNullable(s.toLowerCase()) }

Note that you may omit declaration of type for a the way you did it before. 需要注意的是,你可以省略类型声明a你以前做过的方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM