ant2009 :
kotlin 1.3.31
I have the following code snippet in Java that I am trying to convert to Kotlin
private ArgumentMatcher<List<Person> customArgumentMatcher(final int size) {
return argument -> argument.size() == size;
}
My undestanding of the above is a method declaration that has a ArgumentMatcher as the return type and the method of the interface is executed in the lambda expression and the resulting boolean is returned. Correct me if I am wrong with my explanation.
However, when I try and convert this to Kotlin
private fun customArgumentMatcher(size: Int): ArgumentMatcher<List<Person>> {
return { argument -> argument.size == size }
}
I get the following error:
Required ArgumentMatcher<List<Person>>
found: (???) -> Boolean
Many thanks for any suggestions,
Slaw :
Since ArgumentMatcher
is a Java functional interface you need to use:
fun customArgumentMatcher(size: Int): ArgumentMatcher<List<Person>> {
return ArgumentMatcher { argument -> argument.size == size }
}
See the SAM Conversions section of the Kotlin reference.
You could also use:
fun customArgumentMatcher(size: Int) = ArgumentMatcher<List<Person>> { it.size == size }
See gidds' answer for some background on why the above syntax is necessary.