Is there a way to get reference to lambda in its d...
# getting-started
s
Is there a way to get reference to lambda in its definition?
Copy code
val lambda = { value : Int -> executor( value, this ) }
s
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
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
No, you can't reference it directly. What do you need that for? There's probably a better way to solve your problem.
s
Ok, just trying out few things, nothing specific
g
You could use reflection, like this
Copy code
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
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
Interesting, will check that out
m
@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
yeah, same for me too
m
I found this implementation of the Y-combinator here: https://gist.github.com/jubinjacob19/99989899ddb2d8e1d1055730e6ecace4
Copy code
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):
Copy code
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
🙂