Kotlin JVM Main Class Quirk

November 03, 2019

I was having is odd issue where a shaded Kotlin jar wasn't finding it's main class. I searched around and found a few solutions, but oddly while the code looked like the solution, it still didn't work...

Currently (Kotlin since M14 including up to 1.0 betas), to run a  Kotlin class you are actually running a special class that is created at  the file level that hold your main() and other functions that are top-level (outside of a class or interface).  So if your code is:

package com.my.stuff

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

Then you can execute the program by running the com.my.stuff.AppKt class. This name is derived from your filename with Kt appended (previous versions appended KT but from later betas and 1.0 is Kt). You can change the name of this class within the file by adding this file-targeted annotation: @file:JvmName("MyApp"). Or you can also put your main() into a class with a companion object and make it static using the JvmStatic annotation.  Therefore your class name is the one you chose:

package com.my.stuff

public class MyApp {
    companion object {
        @JvmStatic public fun main(args: Array<String>) {
          ...
        }
    }
}

Now for either of these methods, you just run the class com.my.stuff.MyApp. Frustratingly the second option was briefly a "it works on my machine situation" until it too stopped working. In the end the first option of just annotating the file and leaving the rest as kotlin works just fine:

@file:JvmName("MyApp")

package com.my.stuff

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