I am trying to initialise a basic Kotlin project using Gradle.
I followed this official doc step by step but I am getting this error
Error: Main method not found in class org.example.MainKt, please define the main method as:
public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application
This is my Main.kt file
package org.example
fun main() {
println("Hello World!")
}
This is the build.gradle.kts file.
plugins {
kotlin("jvm") version "2.1.10"
}
group = "org.example"
version = "1.0-SNAPSHOT"
repositories {
mavenCentral()
}
dependencies {
testImplementation(kotlin("test"))
}
tasks.test {
useJUnitPlatform()
}
kotlin {
jvmToolchain(21)
}
Thanks it worked. Is it like java where you need a class with the same name as the file with a static main method? Can you link to documentation, I don’t remember reading that in docs.
The class doesn’t need to be the same name as the file, I think. The issue is a static function in a companion object vs a function in a file.
class Main {
companion object {
@JvmStatic
fun main(args: Array<String>) {
println("Hello World!")
}
}
}
The above code is equivalent to the following Java code:
public class Main {
public static void main(String[] args) {
System.out.println("Hello World!");
}
}
As of around Kotlin 1.3 or so, they added the ability to define a main method outside a companion object. So in theory, you can replace that Kotlin code above, with this:
fun main() {
println("Hello World!")
}
That’s not working for you, and I’m not 100% sure why. But the fix is pretty easy, as I showed you. Hopefully someone who knows more than me can figure out why it doesn’t work if you just put the main method directly in the file.