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
?
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 {
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With