Reputation: 12136
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.
Upvotes: 46
Views: 56829
Reputation: 27226
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.
Upvotes: 5
Reputation: 111
from kotlin 1.7.20 with K2 compiler it is possible.
https://kotlinlang.org/docs/whatsnew1720.html#support-for-kotlin-k2-compiler-plugins
Upvotes: 1
Reputation: 421
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." }
Upvotes: 11
Reputation: 12215
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")
}
}
Upvotes: 1
Reputation: 11676
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/
Upvotes: 11
Reputation: 44130
It's not supported and, by the looks of things, it isn't going to be.
Upvotes: 1
Reputation: 19968
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.
Upvotes: 24
Reputation: 11
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.
Upvotes: -1