Is it possible to use Lombok with Kotlin?

52.9k Views Asked by At

I have a Kotlin Gradle project. I added Lombok as a dependency and also registered it with kapt

compileOnly("org.projectlombok:lombok:$lombokVersion")
kapt("org.projectlombok:lombok:$lombokVersion")

I would like to use the @Slf4j annotation for automatic logger generation. It works for Java classes but not for the Kotlin ones.

Is using Kotlin and Lombok together even possible as of now? If I annotate a Kotlin class with @Slf4j and use log inside it I get

Unresolved reference: log

Evidently no annotation processing is applied.

8

There are 8 best solutions below

0
On BEST ANSWER

You cannot use annotation @Slf4j, but manually create its object in the class required.

Refer https://www.reddit.com/r/Kotlin/comments/8gbiul/slf4j_loggers_in_3_ways/

3
On

I can't see how it would work without additional support from the lombok team. Lombok is based on annotation processing so it runs during compilation time and runs on your source code, so I guess it assumes Java's syntax.

3
On

If all you want to use Lombok for is @Slf4j, then I'd suggest using kotlin-logging instead: https://github.com/MicroUtils/kotlin-logging

It's a simple wrapper around slf4j, so instead of annotating your class with @Slf4j, you use:

// Place definition above class declaration to make field static
private val logger = KotlinLogging.logger {}
// ...

logger.debug { "A message only logged if debug is enabled. With $variable support." }
0
On

Lombok's builder annotation support has been added to kotlin 1.8 as of late December 2022.

You can learn how to configure the plugin here.

In Short, add

plugins {
    id 'org.jetbrains.kotlin.plugin.lombok' version '1.8.0'
    id 'io.freefair.lombok' version '5.3.0'
}

to your Groovy/Gradle files, and/or take a look at the sample project.

2
On

For logging the best I could do - because @Slf4j did not work - was like creating abstract log class like:

package org.example

import org.slf4j.LoggerFactory
import org.slf4j.Logger

abstract class Log {
    val log: Logger = LoggerFactory.getLogger(this.javaClass)
}

and usage:

package org.example

class MyClass { 
    companion object : Log() {}
    @Test
    fun someFun() {
        log.info("Logging info")
    }
}
0
On

Lombok does not run on your source code, but on the AST. Anyway, it is an annotation processor that is run at compile-time by the Java compiler. The Kotlin compiler does not use these annotation processors. See also the answer https://stackoverflow.com/a/35530223/2621917 straight from the horse’s mouth.

0
On

It's not supported and, by the looks of things, it isn't going to be.

0
On