Idiomatic way of logging in Kotlin

后端 未结 16 1471
情歌与酒
情歌与酒 2020-12-07 07:34

Kotlin doesn\'t have the same notion of static fields as used in Java. In Java, the generally accepted way of doing logging is:

public class Foo {
    privat         


        
16条回答
  •  半阙折子戏
    2020-12-07 07:54

    You can simply build your own "library" of utilities. You don't need a large library for this task which will make your project heavier and complex.

    For instance, you can use Kotlin Reflection to get the name, type and value of any class property.

    First of all, make sure you have the meta-dependency settled in your build.gradle:

    dependencies {
        implementation "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version"
    }
    

    Afterwards, you can simply copy and paste this code into your project:

    import kotlin.reflect.full.declaredMemberProperties
    
    class LogUtil {
        companion object {
            /**
             * Receives an [instance] of a class.
             * @return the name and value of any member property.
             */
            fun classToString(instance: Any): String {
                val sb = StringBuilder()
    
                val clazz = instance.javaClass.kotlin
                clazz.declaredMemberProperties.forEach {
                    sb.append("${it.name}: (${it.returnType}) ${it.get(instance)}, ")
                }
    
                return marshalObj(sb)
            }
    
            private fun marshalObj(sb: StringBuilder): String {
                sb.insert(0, "{ ")
                sb.setLength(sb.length - 2)
                sb.append(" }")
    
                return sb.toString()
            }
        }
    }
    

    Example of usage:

    data class Actor(val id: Int, val name: String) {
        override fun toString(): String {
            return classToString(this)
        }
    }
    

提交回复
热议问题