proper way to run kotlin application from gradle task

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


Thanks to the link how to run compiled class file in Kotlin? provided by @JaysonMinard that main

@file:JvmName("Example")

package com.lapots.game.journey.ims.example


fun main(args: Array<String>) {
    print("executable!")
}

and that task

task runExample(type: JavaExec) {
    main = 'com.lapots.game.journey.ims.example.Example'
    classpath = sourceSets.main.runtimeClasspath
}

did the trick


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"
}

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

Tags:

Gradle

Kotlin