2

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?

Jayson Minard
  • 84,842
  • 38
  • 184
  • 227
Xipo
  • 1,765
  • 1
  • 16
  • 23

1 Answers1

4

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.

syntagma
  • 23,346
  • 16
  • 78
  • 134
  • Would you mind to explain why? I mean, my expectation was that I would not have since the type matches. And Kotlin is so good at guessing things like this – Xipo Nov 07 '18 at 22:50
  • 1
    @Xipo I think this is because Kotlin cannot correctly convert it's internal function type to SAM-converted lambda, so when you declared it as `var a: MyRetriever`, there was a type mismatch. See [this blogpost](https://readyset.build/kotlins-sam-problem-f315ffe6be3a) for more information. – syntagma Nov 07 '18 at 22:58