Anonymous classes with lambdas in Kotlin

I am trying to rewrite a leisure project from Java to Kotlin (in order to understand it), and I have encountered some problems. Research led me to { function() } but that didn't help me

In Java, I have this interface:

 public interface Shuffling<T> { List<T> shuffle(List<T> list, ShuffleCallback callback); interface ShuffleCallback { void onShuffle(int addedTo, int randomIndex); } } 

And I'm trying to add a test object to the list of shuffling algorithms in Kotlin:

 val algoList = ArrayList<Shuffling<Int>>() algoList.add(Shuffling { list, callback -> { Timber.d("Test!") ArrayList<Int>() // how to return this value? }}) 

First problem

How to add multiple lines to lambda function?

I also have another example of problems:

Kotlin Interface:

 interface Drawable { fun draw() } 

And the Kotlin implementation:

 private val drawList = ArrayList<Drawable>() //... drawList.add(Drawable {glDrawArrays(GL_TRIANGLE_FAN, startVertex, numVertices)}) 

Second problem

I used to just use:

 mDrawList.add(() -> glDrawArrays(GL_TRIANGLE_FAN, startVertex, numVertices)); 

And everything was in order.

+5
source share
1 answer

OK, so here are the quick fixes:

For your first question: please remove the β€œinner” pair of brackets from your lambda. Now your code does not return an ArrayList<Int>() , but a function that returns a list (when called)

For the second question: the trick you used in the first question called SAM conversion, and only works for java interfaces to match java8. Your Drawable defined in Kotlin, so there is no black magic available, you need to create an instance and pass it:

 drawList.add(object: Drawable { override fun draw() = glDrawArrays(GL_TRIANGLE_FAN, startVertex, numVertices) }) 

for more information read: https://kotlinlang.org/docs/reference/java-interop.html#sam-conversions

PS you do not need to use Shuffling in front of the lambda. This is not needed here (I think), and it makes the code very complicated.

+6
source

Source: https://habr.com/ru/post/1236549/


All Articles