22

In Java, especially in Android studio, every time that I want to run or test some Java source code quickly, I will create public static void main (shortkey: psvm + tab) and the IDE will show "Play" button to run it immediately.

enter image description here

Do we have some kind of psvm in Kotlin - an entry point or something in order to run or test anything that quickly? Did try with this function but it wasn't working. (Even try with @JvmStatic). Can we config somewhere in Android studio?

fun main(args: Array<String>) {

}
phatnhse
  • 3,870
  • 2
  • 20
  • 29

3 Answers3

32

Put it inside a companion object with the @JvmStatic annotation:

class Test {
    companion object {
        @JvmStatic
        fun main(args: Array<String>) {}
    }
}
TheWanderer
  • 16,775
  • 6
  • 49
  • 63
29

You can just put the main function outside of any class.

In anyFile.kt do:

package foo

fun main(args: Array<String>) {

}

enter image description here

Either main + tab or psvm + tab work if you have your cursor outside of a class.

leonardkraemer
  • 6,573
  • 1
  • 31
  • 54
  • Is there a way use it as the main class for the case of running the app as a jar from command line? I only managed to set it up using the companion object + JvmStatic way. – Valerij Dobler Jan 09 '22 at 11:50
  • I have not done Kotlin development in a while and I cant answer your question off the top of my head, but maybe you find your answer here https://stackoverflow.com/a/44290802/4265739 – leonardkraemer Jan 10 '22 at 13:01
-3

Yes, shortkey: main + tab in any kotlin file

It will generate

fun main(args: Array<String>) {

}
Misha Akopov
  • 12,241
  • 27
  • 68
  • 82
Omar Mainegra
  • 4,006
  • 22
  • 30