Idiomatic way of logging in Kotlin

后端 未结 16 1446
情歌与酒
情歌与酒 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:42

    Would something like this work for you?

    class LoggerDelegate {
    
        private var logger: Logger? = null
    
        operator fun getValue(thisRef: Any?, property: KProperty<*>): Logger {
            if (logger == null) logger = Logger.getLogger(thisRef!!.javaClass.name)
            return logger!!
        }
    
    }
    
    fun logger() = LoggerDelegate()
    
    class Foo { // (by the way, everything in Kotlin is public by default)
        companion object { val logger by logger() }
    }
    

提交回复
热议问题