Kotlin lambda / Java SAM interop - type mismatch

388 views Asked by At

I have an existing Java interface defined as follows

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

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?

1

There are 1 answers

2
syntagma On BEST ANSWER

When doing a SAM conversion, you need to explicitly provide a type:

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.