Can I specify which main method to run from the command line?

Hi! When I run programs from Idea I can click the green triangle next to any main() method to run that specific file. There are also keyboard shortcuts for this.

Is there a way to specify which Kotlin file to run when using ./gradlew run? In my case I have over a hundred main methods to generate various visual experiments and it would be nice to be able to launch them from the command line.

Thank you :slight_smile:

If you have a run task, I guess you applied the application plugin.
So configure the application plugin with the main class you want like documented, e.g.

application {
    mainClass.set("org.gradle.sample.Main")
}

You can also register mutliple tasks of type JavaExec for the different main classes if you want to have multiple tasks for the main classes.

Thank you! That was enough to make it work. I added

application {
    if (hasProperty("launch")) {
        mainClass.set("${property("launch")}Kt")
    }
}

to my build.gradle.kts and then I can do ./gradlew run -Plaunch=Hello1 or ./gradlew run -Plaunch=org.foo.Bar to start various programs :slight_smile:

2 Likes