Kotlin Application with Gradle application plugin

2019-06-21 23:18发布

问题:

I am trying to create a simple HelloWorld application using kotlin, gradle, and the gradle application plugin. When I run it with the below setup I get the following error:

Error: Main method is not static in class com.petarkolaric.helloworld.Main, please define the main method as:
public static void main(String[] args)

My build.gradle:

group 'helloworld'
version '1.0-SNAPSHOT'

buildscript {
    ext.kotlin_version = '1.2.0'

    repositories {
        mavenCentral()
    }
    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}

apply plugin: 'kotlin'
apply plugin: 'application'

mainClassName = "com.petarkolaric.helloworld.Main"

repositories {
    mavenCentral()
}

dependencies {
    compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
}

compileKotlin {
    kotlinOptions.jvmTarget = "1.8"
}
compileTestKotlin {
    kotlinOptions.jvmTarget = "1.8"
}

My src/main/kotlin/com/petarkolaric/helloworld/Main.kt:

package com.petarkolaric.helloworld

class Main {

    fun main(args : Array<String>) {
        println("Hello, World!")
    }
}

According to this blog post I should be able to use the application plugin this way.

What do I need to change to allow the application plugin to run my main function when I run gradle run?

回答1:

As the error says, your main method is not static. You have the following options:

1) Put the main into the companion object and make it JvmStatic

class Main {
    companion object {
        @JvmStatic
        fun main(args : Array<String>) {
            println("Hello, World!")
        }
    }
}

2) Change your class to object - than you more or less have a singleton class and make it JvmStatic

object Main {
    @JvmStatic
    fun main(args : Array<String>) {
        println("Hello, World!")
    }
}

3) Place the main outside the class

fun main(args : Array<String>) {
    println("Hello, World!")
}
class Main {
}