I'm using extensively a trick to return multiple v...
# language-proposals
e
I'm using extensively a trick to return multiple values with zero allocations, it's based on the idea of @louiscad, an example:
Copy code
class Vec2(val x: Float, val y: Float) {
    inline fun plus(s: Float, res: (resX: Float, resY: Float) -> Unit) {
        kotlin.contracts.contract { callsInPlace(res, kotlin.contracts.InvocationKind.EXACTLY_ONCE) }
        res(x + s, y + s)
    }
}
This code can then be called as
Copy code
val a = Vec2(0, 1)
val b: Float; val c: Float
a.plus(3) { x, y -> b = x; c = y }
it's useful in hot loops (in 3d real time graphics) or, in Louis' example in Android, where you want to save any allocation you can Now, It'd be nice if Kotlin may automatically destructurize a lambda placed at the last place in a function signature without any allocations. That is something like:
Copy code
val a = Vec2(0, 1)
val (b, c) = a.plus(3) { x, y }
while underneath the compiler would automatically apply the code as shown in the first example Another nice advantage, which would come for "free", it's essentially using an argument parameter as a return one, overcoming the JVM limitation of not considering the return type as part of the function signature
😮 1
👍 1
👍🏼 1
d
You can also save on allocations by having mutable versions of your classes.
e
I know (code was exemplary), but unfortunately it doesn't cover all the cases
I opened a ticket on youtrack