It is not a duplication. The "object" expression is the keyword.
I am trying to integrate Timber Android Library with https://github.com/orhanobut/logger and I need a customLogStrategyForTimber for my needs.
I came up with this logic. But I am having difficulty on initializing the customLogStrategyForTimber
class App : Application() {
// I CREATED THE lateinit VARIABLE
lateinit var customLogStrategyForTimber: LogStrategy
override fun onCreate() {
super.onCreate()
Timber.plant(object : Timber.DebugTree() {
override fun log(
priorityTimber: Int, tagTimber: String?, message: String, t: Throwable?
) {
// USED THE lateinit HERE
customLogStrategyForTimber = object : LogcatLogStrategy() {
override fun log(priority: Int, tag: String?, message: String) {
super.log(priorityTimber, tagTimber, message)
}
}
println("customLogStrategyForTimber: ${::customLogStrategyForTimber.isInitialized}") // PRINTS TRUE
}
})
println("customLogStrategyForTimber OUTSIDE: ${::customLogStrategyForTimber.isInitialized}") // PRINTS FALSE - WHY??
var formatStrategy1 = PrettyFormatStrategy.newBuilder()
// TRYING TO CALL THE lateinit VARIABLE HERE
// NOW, HERE THE lateinit IS NOT INITIALIZED.
.logStrategy(customLogStrategyForTimber)
.build()
Logger.addLogAdapter(AndroidLogAdapter(formatStrategy1))
}
}
The customLogStrategyForTimber is never initialized. Is there a better way to do this logic? Trying to add the entire formatStrategy code inside the first override fun log method results in unexpected behaviour when using Timber logging, so that does not seem to be the easy option.
Crash when running the App
Caused by: kotlin.UninitializedPropertyAccessException: lateinit property customLogStrategyForTimber has not been initialized
Tried using isInitialized as well.
The code inside it never runs.
EDIT:
Created a sample project: https://github.com/shipsywor/demotimberlogger
EDIT 2:
I added println statements to the code above. You will see that ::customLogStrategyForTimber.isInitialized returns False at one point of code and True at another
NOTE: I cannot put formatStrategy code inside of Timber.plant {... }. It results in unexpected behavior.
It looks like you have needlessly created a local val customLogStrategyForTimber, which is only accessible within the
Timber.plant()method. In effect, you're not really using the lateinit var that you have declared at the top of your class. If you just removedvalfrom object declaration inside theTimber.plant()method, your code would work as you intend it to.As it is now, the object that you have declared stays inside the
Timber.plant()method and isn't accessible on the outside.