Is there anything like C# Caller Information in Kotlin?

Caller Information can help create powerful logging functionality with no burden on the caller, on runtime performance, or on compile time.

Is there anything like this in Kotlin?

1 Like

No, but I agree that it would be a useful feature.

On JVM you can use Thread.currentThread().getStackTrace(). Not sure about the rest of the backends, though.

Creating a Throwable is way more expensive at run-time than compile-time generated parameters.

This information is useful regularly, so it would be great if the compiler can simply insert this for you.

Maybe it can be built with a compiler plug-in?

1 Like

Pretty sure that this could be done. All you need to do is replace a property with the right filename, etc. It’s the same concept that was used for coroutineContext in the earlier iteration of the coroutine system, if I remember correctly.


Another option of getting this is to just write a KEEP proposal. I don’t think there would be much arguing about it. And that way it would have a far greater reach than a plug-in.

There is however one question to consider. How should this work with inline functions

fun foo() {
    bar()
}
inline fun bar() {
    println("$magicFilename$magicLineNumber")
}

There is an argument for it to print the file and line number of the callsite of bar. That way you can create your own logging functions. On the other hand you would no longer be able to use this from within other inline functions without confusion. So maybe it should report the file and linenumber of println. Maybe an annotation could be used to change this behaviour

fun foo() {
    bar()
}
inline fun bar() {
    log()
}
@InlineFileInfo
inline fun log() {
     println("$magicFilename$magicLineNumber")
}

Obviously those names should be improved.

1 Like

My bad, I didn’t look at example usage, from description it looked like runtime call.