I have a class ``` class MyClass { companion obj...
# announcements
v
I have a class
Copy code
class MyClass {
  companion object {
    public fun run(args: Array<String>) {
      ...
    }
  }
  public fun main(args: Array<String>) {
    ...
  }
}
How to call
run
from
main
?
d
Just
run(args)
v
Perhaps, that was a bad idea. Can't run it from jar
d
That
main
fun cannot be used as a JVM main method, those need to be static.
p
main
should be a top level function and class name would be
<filename> + Kt
then. Or you can put
main
into a companion object of a class, but then you also need annotate this function with
@JvmStatic
.
v
Many thanks, I've almost broke my brain because of non-runnable jar
πŸ‘ 1
Maybe something wrong with gradle? Even with this trick it does not run
p
what is error message?
v
Error: Could not find or load main class testline.ExampleKt
Project tree
Copy code
src/
β”œβ”€β”€ main
β”‚   β”œβ”€β”€ kotlin
β”‚   β”‚   └── testline
β”‚   β”‚       └── Example.kt
β”‚   └── resources
└── test
    β”œβ”€β”€ kotlin
    β”‚   └── testline
    β”‚       └── ExampleTest.kt
    └── resources
build.gradle.kts:
Copy code
application {
  // Define the main class for the application.
  mainClassName = "testline.ExampleKt"
}

tasks {
  withType<Jar> {
    manifest {
      attributes(mapOf("Main-Class" to application.mainClassName))
    }
  }
}
d
Can you show
Example.kt
?
v
Copy code
package testline

// imports
import java.io.IOException
...
class Example {
  companion object {
    @JvmStatic
    public fun main(args: Array<String>) {
...
    }
  }
}

//fun main(args: Array<String>) {
//  Example.main(args)
//}

// vim: se et ts=2 sw=2 number:
d
When using
companion object
+
@JvmStatic
your
main
method will be in class
Example
, not
ExampleKt
v
Copy code
Exception in thread "main" java.lang.NoClassDefFoundError: org/jline/reader/UserInterruptException
	at testline.Example.<clinit>(Example.kt)
Caused by: java.lang.ClassNotFoundException: org.jline.reader.UserInterruptException
	at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
	at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
	at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:349)
	at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
	... 1 more
Worse
But with
gradle run
it works
I mean with top-level
main
That is commented out
Ok, it's not a secret
Maybe
Thread()
affects?