Is it possible to create an extension function on ...
# getting-started
e
Is it possible to create an extension function on functions?
🚫 1
yes black 2
n
Can you give an example where/how this is going to be used?
e
Yes, I'm thinking of creating something that shows stack growth, as part of a course I'm teaching. If a function was invoked using my extension method, stack information would be displayed
n
Well you can technically investigate function like this using reflection
Or even run it like this, but I don’t think stack information is visible here.
You will need to investigate the JVM itself on runtime
e
Couldn't I get stack information by throwing and immediately catching an exception?
In any case, I'd be happy to fake the stack information.
There are probably better ways of doing what I want, such as creating a map between function names and functions that might be called and creating the extension function on that.
n
The stack information is visible to JVM. I suggest for you to look into a profiler. It gives you the information in there, including thread info, stack info, created objects, etc
🙏 1
j
Copy code
fun (()->Unit).functionInvoker(){
    println("invoking function")
    this()
}
fun helloWorld(){
    println("hello world")
}
fun main(){
    {helloWorld()}.functionInvoker()
}
🥇 1
y
Even better would be calling it like this:
Copy code
::helloWorld.functionInvoker()
e
Java 9 added https://docs.oracle.com/javase/9/docs/api/java/lang/StackWalker.html which is cleaner than misusing a throwable to walk the stack
but it is generally not recommended to create extensions on function types in Kotlin: https://kotlinlang.slack.com/archives/CQ3GFJTU1/p1634832675000100?thread_ts=1634242183.020800&cid=CQ3GFJTU1
e
Thanks! I think I'll give up on the idea.