Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Anonymous classes with lambdas in Kotlin

Tags:

java

kotlin

I'm trying to re-write my leisure time project from Java to Kotlin (to understand it) and I met some problems. Researches brought me to { function() } but It 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 test object to 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 trouble

How to add multiple lines to lambda function?

Also I have another example with troubles:

Kotlin interface:

interface Drawable {
    fun draw()
}

And Kotlin implementation:

private val drawList = ArrayList<Drawable>()

//...
drawList.add(Drawable {glDrawArrays(GL_TRIANGLE_FAN, startVertex, numVertices)})

Second trouble

Previously I used just:

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

And everything was OK.

like image 348
Anton Shkurenko Avatar asked Nov 22 '15 13:11

Anton Shkurenko


1 Answers

OK, so here are the quick fixes:

For your first question: please remove the "internal" pair of brackets from your lambda. Now your code returns not ArrayList<Int>(), but a function that returns the list (when invoked)

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

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

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

P.S you do not have to use Shuffling before a lambda. It is not needed here (I guess) and it complicates the the code a lot.

like image 152
voddan Avatar answered Oct 02 '22 06:10

voddan