Search code examples
kotlinkotlin-interop

Kotlin lambda / Java SAM interop - type mismatch


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?


Solution

  • 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.