3

I need to convert a gradle build script, which is written in Groovy, into Kotlin. The problem is, that in the Groovy build file in one task another task, which was defined before, is executed. However, it appears that in Kotlin there is no support for that, at least I could not find any in the API.

I have studied the API and searched for similar problems, but I could not find anything useful.

The Groovy code looks like this:

task doSomething () {
   ...
}
task anotherTask () {
   ...
   doSomething.execute()
   ...
}

How would this call be translated into Kotlin?

doSomething.execute()
1
  • The method execute is not available in Gradle anymore (since 5.0), so this is not caused by a difference between Groovy and Kotlin. It is often found in older builds, but should actually never be used, because it may interfere with the Gradle task execution system. Commented Aug 18, 2019 at 1:49

2 Answers 2

6

You should never call execute() on a task. Instead set the inputs, outputs and dependencies correctly, and Gradle will call the task for you if it needs to.

something like:

tasks {
    val doSomething by registering {
        doLast {
            println("running doSomething")
        }
    }

    val anotherTask by registering {
        dependsOn(doSomething)
        doLast {
             println("Running anotherTask")
        } 
    }
}

Then:

$ gradle anotherTask

> Task :doSomething
running doSomething

> Task :anotherTask
Running anotherTask

BUILD SUCCESSFUL in 746ms
Sign up to request clarification or add additional context in comments.

Comments

3

Kotlin is statically typed. So you must know the type of the task of doSomething and anotherTask if Kotlin not able to infer it for you. execute leads me to believe it some sort of execute task. So for your example:

val doSomething = tasks.register("doSomething", JavaExec::class.java) {
    main = "com.example.Example"
}

val anotherTask = tasks.register("anotherTask") {
    doSomething.get().exec()
}

However, it looks you just want to execute doSomething before anotherTask, so you'd want:

val doSomething = tasks.register("doSomething", JavaExec::class.java) {
    main = "com.example.Example"
}

val anotherTask = tasks.register("anotherTask") {
    dependsOn(doSomething)
}

Without knowing the types of your task it's difficult to give you the right answer.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.