Convenient Kotlin LoggerFactory simplification - android

What is the most convenient way to use SLF4J or other logging approaches with kotlin?
Usually the developer is busy with boilerplate code like
private val logger: Logger = LoggerFactory.getLogger(this::class.java)
in each and every class to get a proper logger?
What are the most convenient ways to unify/simplify this with Kotlin?

You can define an extension property on every type:
val <T : Any> T.logger: Logger
get() = LoggerFactory.getLogger(this::class.java)
use it as follows:
class X {
init {
logger.debug("init")
}
}

Here's a simple example which returns a lazily-initialized logger from a bound callable reference or a standard property. I prefer calling from a callable reference because the :: denotes reflection (related to logging).
The class which provides the Lazy<Logger>:
class LoggingProvider<T : Any>(val clazz: KClass<T>) {
operator fun provideDelegate(inst: Any?, property: KProperty<*>) =
lazy { LoggerFactory.getLogger(clazz.java) }
}
Inline functions to call them:
inline fun <reified T : Any> KCallable<T>.logger() =
LoggingProvider(T::class)
inline fun <reified T : Any> T.logger() =
LoggingProvider(T::class)
Here's an example of using them. The require assertion in the initializer shows that the loggers share a reference:
class Foo {
val self: Foo = this
val logger by this.logger()
val callableLogger by this::self.logger()
init {
require(logger === callableLogger)
}
}

I define this function in my projects to make defining a logger easier for me. It takes advantage of Kotlin's reified types.
// Defined in Utilities.kt
inline fun <reified T:Any> logFor() =
LoggerFactory.getLogger(T::class.java)
Usage:
class MyClass {
private val log = logFor<MyClass>()
...
}
Or if you are creating a lot of them:
class MyClass {
companion object {
private val log = logFor<MyClass>()
}
...
}

if you don't like the boilerplate, you can always wrap the log.info with your own logger helper:
mylog.info(this, "data that needs to be logged")
Then in the background, have some sort of hashmap that keeps track of classes of the this param that can instantiate a logger for that class.
Other options might be using AspectJ Weaving to weave a logger into each class, but this is overkill in my opinion.

I have defined a utility method for this
fun getLogger(cl: KClass<*>): Logger {
return LoggerFactory.getLogger(cl.java)!!
}
and now in each class I can use the logger like this
companion object {
private val logger = getLogger(MyClass::class)
}

Related

Question regarding delegation of Viewmodel property(Android)(Kotlin)

Whenever I am trying to delegate my viewmodel using the delegated property in my Fragments
val viewModel:NewsViewModel by activityViewModels<> { }
This is the error I would receive.
Property delegate must have a 'getValue(BreakingNews, KProperty*>)' method. None of the following functions are suitable.
Lazy<NewsViewModel>.getValue(Any?, KProperty<*>)   
where T = NewsViewModel for inline operator fun <T> Lazy<T>.getValue(thisRef: Any?, property:
KProperty<*>): T defined in kotlin
However, instantiating the viewmodel instance in the MainActivity this way, seems fine
val viewmodelFactory = ViewModelProviderFactory(dataRepo)
viewModel = ViewModelProvider(this,viewmodelFactory).get(NewsViewModel::class.java)
I assumed at first it may be due to the viewmodelFactory which is as follows.
class ViewModelProviderFactory(val Repo:NewsRepository): ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>,extras: CreationExtras): T {
return NewsViewModel(Repo) as T
}
}
The code below are the properties in my ViewModel, This is odd as I have cross-referred from multiple sources including the official `docs.
var breakingNews: MutableLiveData<Resource<ArticleList>> = MutableLiveData()
var breakingNewsPage = 1
var breakingNewsResponse: ArticleList? = null
var searchNews: MutableLiveData<Resource<ArticleList>> = MutableLiveData()
var searchNewsPage = 1
var searchNewsResponse: ArticleList? = null
var savedNumerics = 0
var _status = MutableLiveData<String>()
....
}
Usually, you want just val viewModel:NewsViewModel by activityViewModels().
In your case, with val viewModel:NewsViewModel by activityViewModels<> { }, you skipped two things.
First, you are attempting to provide a value for the extrasProducer parameter to the activityViewModels() function. However, that lambda expression needs to evaluate to a CreationExtras object, and yours evaluates to Unit.
Second, you failed to provide a type. AFAIK, <> is not going to be valid syntax here. Either leave the <> off (and the compiler should infer the type from the property type) or fully qualify it as <NewsViewModel>. I think this is the cause of your specific syntax error, but even if you fix this, you should then run into a problem with your empty lambda expression.

Dynamic lazy initialization for val in kotlin

I understand there are two ways for lazy initialization in kotlin. first by lateinit which is dynamic but it is only for var. second, by lazy delegate which is for val but it is static, which means it can't be initialized at runtime.
I was wondering is there a way to have lazy dynamic initialization for immutable properties(val)????
property delegation also works like lazy and even if we define a custom delegate, its always static initialization. (to my knowledge)
is there a workaround for this? could it be implemented somehow?
so what I wish for, is something like lateinit val, shown in below code:
class MyClass: SomeCallback {
private lateinit val myData: String
override fun onStatusChanged(status: Status, data: String) {
if(status == Status.DataConfirmed ) {
myData = data
}
}
}
The best I can come up with is a read-write property delegate that throws if you access it before setting it, or if you set it multiple times. Kotlin doesn't let you lateinit a val. This is likely because it would be nonsensical to call a setter for a property that doesn't have one. I doubt they want to introduce the can of worms it would be to directly set the value of a backing field from anywhere besides the initializer, because it would be ambiguous.
A delegate like this should be adequate. If it's not adequate to help you immediately fix the bug of calling the setter multiple times, I would say that's a code smell that the class is too complicated and needs to be broken up into smaller units.
class Once<T>: ReadWriteProperty<Any, T> {
private object UNINITIALIZED
private var _value: Any? = UNINITIALIZED
override fun getValue(thisRef: Any, property: KProperty<*>): T {
if (_value !== UNINITIALIZED) {
#Suppress("UNCHECKED_CAST")
return _value as T
}
throw UninitializedPropertyAccessException("Property [$property] was accessed before it was initialized.")
}
override fun setValue(thisRef: Any, property: KProperty<*>, value: T) {
if (_value === UNINITIALIZED) {
_value = value
} else {
error("Cannot set property [$property] more than once.")
}
}
}

Kotlin : Casting an object to Generic class

How get the type of a Generic class and cast an object to it?
I want to use this function to pass an Interface class:
protected fun <T> getInteraction(): T {
return when {
context is T -> context
parentFragment is T -> parentFragment as T
else -> throw IllegalArgumentException("not implemented interaction")
}
}
and use it like:
private var interaction: ISigninInteraction? = null
override fun onAttach(context: Context?) {
super.onAttach(context)
interaction = getInteraction<ISigninInteraction>()
}
Kotlin, Java and JVM do have types erasure when Generics are implemented. Generics are not visible at the bytecode level. It means, you cannot use type parameters, e.g. T, directly in the function code.
Kotlin adds support for reified generics, which helps here. You may declare the function like
inline fun <reified T> getIt() : T {
...
}
With the help of reified and inline it will be possible to cast to T and return it.
https://kotlinlang.org/docs/reference/inline-functions.html#reified-type-parameters
The second alternative is to follow a Java practice - add the Class<T> parameter to the function and use Class#cast to cast to T instead.
You may combine the reified inline function with the approach like:
inline fun <reified T> getIt() = getIt(T::class.java)

Android data binding with Kotlin, BaseObservable, and a custom delegate

I'm attempting to write a custom delegate which would clean up the syntax for databinding in a Kotlin class. It would eliminate the need to define a custom getter and setter for every property I might want to observe.
The standard implementation in Kotlin appears to be as follows:
class Foo : BaseObservable() {
var bar: String
#Bindable get() = bar
set(value) {
bar = value
notifyPropertyChanged(BR.bar)
}
}
Clearly, with a lot of properties this class can become pretty verbose. What I would like instead is to abstract that away into a delegate like so:
class BaseObservableDelegate(val id: Int, private val observable: BaseObservable) {
#Bindable
operator fun getValue(thisRef: Any, property: KProperty<*>): Any {
return thisRef
}
operator fun setValue(thisRef: Any, property: KProperty<*>, value: Any) {
observable.notifyPropertyChanged(id)
}
}
Then, the class which extends BaseObservable could go back to having one-line variable declarations:
class Foo : BaseObservable() {
var bar by BaseObservableDelegate(BR.bar, this)
}
The problem is that without the #Bindable annotation in the Foo class, no propertyId is generated in BR for bar. I'm unaware of any other annotation or method for generating that property id.
Any guidance would be appreciated.
You can annotate the default getter or setter without providing a body.
var bar: String by Delegates.observable("") { prop, old, new ->
notifyPropertyChanged(BR.bar)
}
#Bindable get
There is a shortcut annotation use-site target which does the same thing.
#get:Bindable var bar: String by Delegates.observable("") { prop, old, new ->
notifyPropertyChanged(BR.bar)
}
Additionaly to the accepted answer - sometimes you need variables passed in constructor. It is easy to do too.
class Foo(_bar: String) : BaseObservable() {
#get:Bindable var bar by Delegates.observable(_bar) { _, _, _ ->
notifyPropertyChanged(BR.bar)
}
}
Sometimes we have to save object using parcel, I had some problems using delegete, so code looks like this:
#Parcelize
class Foo(private var _bar: String) : BaseObservable(), Parcelable {
#IgnoredOnParcel
#get:Bindable var bar
get() = _bar
set(value) {
_bar = value
notifyPropertyChanged(BR.bar)
}
}
I considered using the androidx.databinding.ObservableField wrapper for my fields. However, it was quite annoying having to read the values as field.get() and write them field.set(value) from the Kotlin code. Also, this approach does require special converters for serialization if you are using it with Retrofit or Room Database.
Finally, I came up with the below approach which allows me to define the variable in a single line as oppose to the accepted answer and keep the field to their default type without any wrapper. Thanks to the Kotlins property delegation. Now, I don't have to write converters for the serialization and have all the benefit from databinding.
class ObservableField<T : BaseObservable, V>(initialValue: V, private val fieldId: Int = -1) : ReadWriteProperty<T, V> {
private var value: V = initialValue
override fun getValue(thisRef: T, property: KProperty<*>): V {
return value
}
override fun setValue(thisRef: T, property: KProperty<*>, value: V) {
this.value = value
if (fieldId == -1) {
thisRef.notifyChange()
} else {
thisRef.notifyPropertyChanged(fieldId)
}
}
}
class Credential: BaseObservable() {
var username: String by ObservableField("")
#get:Bindable var password: String by ObservableField("", BR.password)
}

Kotlin object (singleton) with an Android Application Context [duplicate]

This question already has answers here:
Singleton with parameter in Kotlin
(14 answers)
Closed 2 years ago.
The Kotlin reference says that I can create a singleton using the object keyword like so:
object DataProviderManager {
fun registerDataProvider(provider: DataProvider) {
//
}
}
However, I would like to pass an argument to that object. For example an ApplicationContext in an Android project.
Is there a way to do this?
Since objects do not have constructors what I have done the following to inject the values on an initial setup. You can call the function whatever you want and it can be called at any time to modify the value (or reconstruct the singleton based on your needs).
object Singleton {
private var myData: String = ""
fun init(data: String) {
myData = data
}
fun singletonDemo() {
System.out.println("Singleton Data: ${myData}")
}
}
Kotlin has a feature called Operator overloading, letting you pass arguments directly to an object.
object DataProviderManager {
fun registerDataProvider(provider: String) {
//
}
operator fun invoke(context: ApplicationContext): DataProviderManager {
//...
return this
}
}
//...
val myManager: DataProviderManager = DataProviderManager(someContext)
With most of the existing answers it's possible to access the class members without having initialized the singleton first. Here's a thread-safe sample that ensures that a single instance is created before accessing any of its members.
class MySingleton private constructor(private val param: String) {
companion object {
#Volatile
private var INSTANCE: MySingleton? = null
#Synchronized
fun getInstance(param: String): MySingleton = INSTANCE ?: MySingleton(param).also { INSTANCE = it }
}
fun printParam() {
print("Param: $param")
}
}
Usage:
MySingleton.getInstance("something").printParam()
There are also two native Kotlin injection libraries that are quite easy to use, and have other forms of singletons including per thread, key based, etc. Not sure if is in context of your question, but here are links to both:
Injekt (mine, I'm the author): https://github.com/kohesive/injekt
Kodein (similar to Injekt): https://github.com/SalomonBrys/Kodein
Typically in Android people are using a library like this, or Dagger, et al to accomplish parameterizing singletons, scoping them, etc.
I recommend that you use this form to pass arguments in a singleton in Kotlin debit that the object your constructor is deprived and blocked:
object Singleton {
fun instance(context: Context): Singleton {
return this
}
fun SaveData() {}
}
and you call it this way in the activity
Singleton.instance(this).SaveData()
If you looking for a base SingletonHolder class with more than one argument. I had created the SingletonHolder generic class, which supports to create only one instance of the singleton class with one argument, two arguments, and three arguments.
link Github of the base class here
Non-argument (default of Kotlin):
object AppRepository
One argument (from an example code in the above link):
class AppRepository private constructor(private val db: Database) {
companion object : SingleArgSingletonHolder<AppRepository, Database>(::AppRepository)
}
// Use
val appRepository = AppRepository.getInstance(db)
Two arguments:
class AppRepository private constructor(private val db: Database, private val apiService: ApiService) {
companion object : PairArgsSingletonHolder<AppRepository, Database, ApiService>(::AppRepository)
}
// Use
val appRepository = AppRepository.getInstance(db, apiService)
Three arguments:
class AppRepository private constructor(
private val db: Database,
private val apiService: ApiService,
private val storage : Storage
) {
companion object : TripleArgsSingletonHolder<AppRepository, Database, ApiService, Storage>(::AppRepository)
}
// Use
val appRepository = AppRepository.getInstance(db, apiService, storage)
More than 3 arguments:
To implement this case, I suggest creating a config object to pass to the singleton constructor.

Categories

Resources