8

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?

petarkolaric
  • 385
  • 3
  • 16

1 Answers1

19

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 {
}
guenhter
  • 11,255
  • 3
  • 35
  • 66
  • 2
    Options 1 and 2 work, but I think option 3 is what I'd prefer. When I try it, however, it appears that gradle can no longer find the main method: `Error: Main method not found in class com.petarkolaric.helloworld.Main, please define the main method as: public static void main(String[] args)` Do you have any idea why this is? – petarkolaric Dec 12 '17 at 06:38
  • 10
    Because the class name changes: it will be `MainKt` if your file is called `Main.kt`. – Alexey Romanov Dec 12 '17 at 06:54
  • I see - top level functions are compiled into their own class which you need to reference from the build.gradle. Thanks! – petarkolaric Dec 12 '17 at 08:44
  • 2
    For your example 3) it is worth mentioning that you can omit the `class Main {}` part and what Alexey said of course. – Giszmo Jan 28 '19 at 21:11