https://kotlinlang.org logo
Title
s

Sam

10/12/2018, 9:29 PM
Is there a way to get reference to lambda in its definition?
val lambda = { value : Int -> executor( value, this ) }
s

stephan_marshay

10/12/2018, 9:31 PM
Do you want a reference to the lambda (to what purpose..?) or to the class containing the lambda? In the second case, use
this@myClass
s

Sam

10/12/2018, 9:35 PM
reference to the lambda
is it even possible?
from a Java standpoint, it is just an implementation of Function1, so i'm guessing there should be way to get its this
m

marstran

10/12/2018, 9:38 PM
No, you can't reference it directly. What do you need that for? There's probably a better way to solve your problem.
s

Sam

10/12/2018, 9:39 PM
Ok, just trying out few things, nothing specific
g

gcx11

10/12/2018, 9:51 PM
You could use reflection, like this
val lambda: (Int) -> String = { value : Int -> executor( value, ::lambda.get() ) }

fun executor(value: Int, body: (Int) -> String): String {
    return body(value)
}

fun main(args: Array<String>) {
    println(lambda(1))
}
👍 1
m

marstran

10/12/2018, 9:52 PM
In theory, you could kinda do it with a construct called a Y-combinator though. The idea is to let the function take itself as a parameter.
👍 1
s

Sam

10/12/2018, 9:52 PM
Interesting, will check that out
m

marstran

10/12/2018, 9:56 PM
@gcx11 For some reason, that seems to compile only when
lambda
is a top level property.
Probably because a local
val
won't have a getter.
s

Sam

10/12/2018, 9:56 PM
yeah, same for me too
m

marstran

10/12/2018, 10:00 PM
I found this implementation of the Y-combinator here: https://gist.github.com/jubinjacob19/99989899ddb2d8e1d1055730e6ecace4
fun <In, Out> y(f: ((In) -> Out) -> (In) -> Out) : (In) -> Out = {
    f(y(f))(it)
}
With that function you can do this (assuming executor returns String):
val lambda = y<Int, String> { f -> { value : Int -> executor(value, f) } }
I don't understand how that Y-combinator works, but it does the job 😛
Please don't write code like that in real life 😛
s

Sam

10/12/2018, 10:00 PM
🙂