I am trying to create a Logger class in android , which would log message only if its a debug build.
object Logger2 {
private const val TAG = Constants.LOGGING_TAG
fun d(message : Any?){
if (BuildConfig.DEBUG)
Log.d(TAG , message.toString())
}
fun d(message: Any? , e : Exception?){
if (BuildConfig.DEBUG)
Log.d(TAG , message.toString(), e)
}
fun e(message : Any?){
if (BuildConfig.DEBUG)
Log.e(TAG , message.toString())
}
fun e(message: Any? , e : Exception?){
if (BuildConfig.DEBUG)
Log.e(TAG , message.toString(), e)
}
fun w(message : Any?){
if (BuildConfig.DEBUG)
Log.w(TAG , message.toString())
}
fun w(message: Any? , e : Exception?){
if (BuildConfig.DEBUG)
Log.w(TAG , message.toString(), e)
}
fun v(message : Any?){
if (BuildConfig.DEBUG)
Log.v(TAG , message.toString())
}
fun v(message: Any? , e : Exception?){
if (BuildConfig.DEBUG)
Log.v(TAG , message.toString(), e)
}
}
Since I want all of my other activities and classes to be able to use this logger class , I created the class as a kotlin object.
This works fine in all other kotlin classes ,I was able to call the log methods like this , This is how I call from the kotlin classes.
Logger2.e("message")
But from a Java class when I try to do the same call . I get this sort of error.

Can someone tell me what exactly does that error mean and how to fix it ? The method from which I am calling the Logger2 class is not even static . Then why this error ?
Kotlin objects are not exactly equivalent to Java static. They are singletons. They exist as a class instance. When accessed from Java, the singleton instance must be retrieved through the static field named INSTANCE:
Logger2.INSTANCE.e("foo");
If you want the compiler to instead make each of these functions static so you don't have to retrieve them through the singleton instance, then mark them as @JvmStatic:
object Logger2 {
@JvmStatic
fun d(message : Any?){
if (BuildConfig.DEBUG)
Log.d(TAG , message.toString())
}
//...
}
The documentation about this is here.
If you're curious about the reasons why it was designed this way:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With