Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

public static void main in Kotlin

Tags:

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>) {

}
like image 610
nhp Avatar asked Dec 31 '18 16:12

nhp


People also ask

What is public static void main?

The keyword public static void main is the means by which you create a main method within the Java application. It's the core method of the program and calls all others. It can't return values and accepts parameters for complex command-line processing.

Is public static void main () is correct?

Yes, we can change the order of public static void main() to static public void main() in Java, the compiler doesn't throw any compile-time or runtime error. In Java, we can declare access modifiers in any order, the method name comes last, the return type comes second to last and then after it's our choice.

What is static in Kotlin?

Android Dependency Injection using Dagger with Kotlin In Java, once a method is declared as "static", it can be used in different classes without creating an object. With static methods, we don't have to create the same boilerplate code for each and every class.

What is public static void main args?

public static void main(String[] args) Java main method is the entry point of any java program. Its syntax is always public static void main(String[] args) . You can only change the name of String array argument, for example you can change args to myStringArgs .


2 Answers

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

class Test {
    companion object {
        @JvmStatic
        fun main(args: Array<String>) {}
    }
}
like image 162
TheWanderer Avatar answered Sep 17 '22 15:09

TheWanderer


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.

like image 44
leonardkraemer Avatar answered Sep 19 '22 15:09

leonardkraemer