A static method in a companion object is placed onto the enclosing class. So in your case MyApp
. This is true regardless of you naming the companion object, and you do not need to reference the companion in any way when running the class.
Therefore your code is correct, assuming the following is true:
- You have the application plugin applied in your Gradle
- You named your package containing the code above as
path.to.application
(you don't show package statement)
- You are getting a class not found error for
path.to.application.MyApp
and that matches #2, (you don't show the actual error from Gradle)
- You are running the correct gradle task (which task are you running?)
- The code is actually compiled, looking at your latest comments indicates you likely had a compiler error (
launch()
method not accessible from companion) which meant that you couldn't run something not yet compiled.
What you can do to check the classname is right click on the main()
method within Intellij IDEA and pick create path.to.app...
menu option that is just below run/debug options and when that opens the runtime configuration dialog you can see the full classname there. That should be the same one used in your Gradle. If you already have a runtime configuration, just view the full classname there. If this does not work, the problem is elsewhere and you need to provide the missing information (what Gradle task, what is the actual error, what is the package statement for the class)
Some information is missing from the question that would help narrow this down.
This example:
package org.test.kotlin
class MyApp {
companion object Launcher {
@JvmStatic
fun main(args: Array<String>) {
println("hello")
}
}
}
Works fine when running class org.test.kotlin.MyApp
So does this, without the word Launcher
:
package org.test.kotlin
class MyApp {
companion object {
@JvmStatic
fun main(args: Array<String>) {
println("hello")
}
}
}
And this works by accident but is not doing what you expected, but is creating a nested class and adding the static there and run using class org.test.kotlin.MyApp.Launcher
. If this is working, then the question isn't showing the actual main classname it is using that is failing:
package org.test.kotlin
class MyApp {
object Launcher {
@JvmStatic
fun main(args: Array<String>) {
println("hello")
}
}
}
About possible compiler errors (#5 above): In your code you reference the launch()
method which you do not show, maybe it is in the ancestor class. But you did not create an instance of any class. So this will fail with compiler error. Change this to:
class MyApp: App() {
override val primaryView = MyView::class
companion object {
@JvmStatic
fun main(args: Array<String>): Unit {
MyApp().launch(*args)
}
}
}
Similar tips are in these other related questions: