kotlincompanion-objectextension-functionkotlin-companion

Companion object with extension function in kotlin?


I would like to have extension function and use logger from kotlin-logging and have constants inside companion object.

My function:

fun String.toFoo(): Foo {

    logger.debug { "Mapping [$this] to Foo" }

    if(MY_CONST.equals(this) { 
        ...
}

Question is where I should put val logger = KotlinLogging.logger {} and MY_CONST since I cannot use companion object with an extension function?


Solution

  • If you just want you logger to be a singleton you can make an object that contains and instance of the logger and reach it from there.

    Object LoggerSingleton( val logger = KotlinLogging.logger{})
    

    Then in your extension function

    fun String.toFoo(): Foo {
    
    LoggerSingleton.logger.debug { "Mapping [$this] to Foo" }
    
    if(MY_CONST.equals(this) { 
     }
    

    Since an Object in Kotlin is guaranteed to have only one instance you won't have a different logger for each use of toFoo.

    EDIT To keep the desired class name Use this signature Like so:

    Object StringLoggerSingleton( val logger = KotlinLogging.logger("String"))