简体   繁体   中英

Referencing kotlin gradle script varaibles in plugins block

I've been writing Gradle plugins in several languages using their usual Groovy build script DSL for some time. As of recently I wanted to learn how to use their Kotlin build script DSL but I can't quite figured out some things.

I have an example below:

val kotlin_version = "1.2.41"

plugins {
    application
    kotlin("jvm").version(kotlin_version)
}

application {
    mainClassName = "samples.HelloWorldKt"
}

dependencies {
    compile(kotlin("stdlib"))
}

repositories {
    jcenter()
}

However, when I run a simple task like 'clean', I get the following error:

* What went wrong:
Script compilation error:

  Line 5:     kotlin("jvm") version kotlin_version
                                    ^ Unresolved reference: kotlin_version

However, if I replace kotlin_version with a string literal, it works fine:

val kotlin_version = "1.2.41"

plugins {
    application
//    kotlin("jvm").version(kotlin_version)
    kotlin("jvm").version("1.2.41")
}

application {
    mainClassName = "samples.HelloWorldKt"
}

dependencies {
    compile(kotlin("stdlib"))
}

repositories {
    jcenter()
}

However, if I parameterize the dependencies block with my kotlin_version , it works perfectly fine:

dependencies {
    compile(kotlin("stdlib", kotlin_version))
}

Why can't variables be referenced inside of the plugins block?

See documentation: https://docs.gradle.org/current/userguide/plugins.html#sec:constrained_syntax Basically, it states that plugin version must be constant, literal, string.

It is achieved by DslMaker: https://kotlinlang.org/docs/reference/type-safe-builders.html#scope-control-dslmarker-since-11

If you want to reuse variable elsewhere, you could use this:

buildscript {
    var kotlinVersion: String by extra { "1.2.41" }

    repositories {
        jcenter()
    }

    dependencies {
        classpath(kotlin("gradle-plugin", kotlinVersion))
    }
}

plugins {
    application
}

application {
    mainClassName = "samples.HelloWorldKt"
}

apply {
    plugin("kotlin")
    plugin("application")
}

val kotlinVersion: String by extra

repositories {
    jcenter()
}

dependencies {
    compile(kotlin("stdlib-jdk8", kotlinVersion))
}

tasks.withType<KotlinCompile> {
    kotlinOptions.jvmTarget = "1.8"
}

If you don't need that, you can simply inline content of variable kotlin_version

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM