'proper way to run kotlin application from gradle task
I've got simple script
package com.lapots.game.journey.ims.example
fun main(args: Array<String>) {
println("Hello, world!")
}
And here is gradle task
task runExample(type: JavaExec) {
main ='com.lapots.game.journey.ims.example.Example'
classpath = sourceSets.main.runtimeClasspath
}
But when I try to run task gradle runExample I get error
Error: Could not find or load main class com.lapots.game.journey.ims.example.Example
What is the proper way to run application?
Solution 1:[1]
In case you're using a Kotlin buildfile build.gradle.kts you would need to do
apply {
plugin("kotlin")
plugin("application")
}
configure<ApplicationPluginConvention> {
mainClassName = "my.cool.App"
}
If you apply the application plugin using the plugins {} block instead you could make it simpler:
plugins {
application
}
application {
mainClassName = "my.cool.App"
}
For details see https://github.com/gradle/kotlin-dsl/blob/master/doc/getting-started/Configuring-Plugins.md
Solution 2:[2]
You can also use gradle application plugin for this.
// example.kt
package com.lapots.game.journey.ims.example
fun main(args: Array<String>) {
print("executable!")
}
add this to your build.gradle
// build.gradle
apply plugin: "application"
mainClassName = 'com.lapots.game.journey.ims.example.ExampleKt'
Then run your application as follows.
./gradlew run
Solution 3:[3]
I found another way from the @lapots answer.
In your example.kt:
@file:JvmName("Example")
package your.organization.example
fun main(string: Array<String>) {
println("Yay! I'm running!")
}
Then in your build.gradle.kts:
plugins {
kotlin("jvm") version "1.3.72"
application
}
application {
mainClassName = "your.organization.example.Example"
}
Solution 4:[4]
For build.gradle.kts users
main file:
package com.foo.game.journey.ims.example
fun main(args: Array<String>) {
println("Hello, world!")
}
build.gradle.kts file:
plugins {
application
kotlin("jvm") version "1.3.72" // <-- your kotlin version here
}
application {
mainClassName = "com.lapots.game.journey.ims.example.ExampleKt"
}
...
And run with the following command:
./gradlew run
Solution 5:[5]
it is possible to do it without adding package name. Run your app with the green play icon and it should show the main class name at the end of the command it runs.

inside build.gradle add className and application like this
plugins {
id 'org.jetbrains.kotlin.jvm' version '1.5.10'
id 'application'
}
mainClassName = 'AppKt'
...
now you can do ./gradlew run and to pass arguments also add --args='foo --bar'
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Egor Neliuba |
| Solution 3 | Jerv Norsk |
| Solution 4 | Lukas Kirner |
| Solution 5 | George Shalvashvili |
