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?
}})
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)})
Previously I used just:
mDrawList.add(() -> glDrawArrays(GL_TRIANGLE_FAN, startVertex, numVertices));
And everything was OK.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With