Is it possible to use context receivers with kotli...
# gradle
j
Is it possible to use context receivers with kotlin-dsl in gradle scripts? I saw that gradle 7.6 updated embedded kotlin to 1.7.10, but I still can’t use context receivers in gradle scripts:
java.lang.UnsupportedOperationException: Unsupported receiver value: Cxt { context(org.gradle.api.Project) [...]
1
c
For Gradle Kotlin DSL, while the embedded Kotlin was upgraded to 1.7.10, the Kotlin compile tasks default to Kotlin 1.4. Adjust with this:
Copy code
// afterEvaluate required as kotlin dsl plugin sets its defaults in afterEvaluate
// <https://github.com/gradle/gradle/blob/master/subprojects/kotlin-dsl-plugins/src/main/kotlin/org/gradle/kotlin/dsl/plugins/dsl/KotlinDslCompilerPlugins.kt#L43>

afterEvaluate {
    tasks.withType<KotlinCompile>().configureEach {
        kotlinOptions {
            freeCompilerArgs += "-Xsam-conversions=class"
            apiVersion = "1.7"
            languageVersion = "1.7"
        }
    }
}
j
Thank you very much. That helped 🙌 I guess
sam-conversions=class
is not required, right?
c
correct, that is there for a different reason to due to configuration cache.
v
Not so much configuration cache, or at least not only. It is more that with newer Kotlin the SAM lambdas get compiled into indy bytecode instructions and such tasks would always be out of date as the classpath changes with each invocation and actually you get a deprecation warning. With that setting the SAM lambdas keep getting compiled as anonymous classes and thus the classpath does not change.
In Gradle 8.0 RC1 this should also be set by the plugin already
m
@handstandsam wrote about this kotlin-dsl forcing the language version here: https://handstandsam.com/2022/04/13/using-the-kotlin-dsl-gradle-plugin-forces-kotlin-1-4-compatibility/
I personaly like to create convention plugins that call use
embedded-kotlin
instead of
kotlin-dsl
, this way, it "feels" more like a generic Kotlin project. Only one that uses the same Kotlin version as the Gradle compiling it
c
there’s already an
embedded-kotlin
plugin.
oh, I see what you mean. Yes. wrap this up in something else.
298 Views