Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

converting a java method to kotlin. Return a lambda expression

Tags:

java

kotlin

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 understanding 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,

like image 635
ant2009 Avatar asked Jun 07 '26 07:06

ant2009


1 Answers

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.

like image 121
Slaw Avatar answered Jun 10 '26 12:06

Slaw



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!