Probably I miss something very simple, but let's imagine I have this extension method in Kotlin:
fun Any.log(message: String) {
println(this.javaClass.simpleName + message)
}
Is it possible to call it from the static method in Java class?
Note. From the regular instance method, I can do
MyExtensionsKt.log(this, "This is a log message")
But the static method doesn't have an object instance.
You could just pass a random
Objectin:Of course, this will produce a log message that starts with
Object, not the name of the current class.To produce a log message that starts with the name of the current class, you would need to either create a new, temporary instance of the current class:
or change the implementation of the
logmethod to be a bit smart about its receiver. For example, if it is found that it is aClass, then just directly use its name as the prefix for the log message.If you cannot do either of those things, then I would suggest that you not use a static method. How about the singleton pattern instead?
Example:
Side note:
Singletons are also how Kotlin's
objects are implemented in the JVM.When you call
Foo.foo(), it may seem like you are calling a "static" method, but you are really just callingFoo.INSTANCE.foo(). Because of this,thisis available in Kotlinobjects.