4

I am new to Kotlin development and I have created a separate Kotlin class in Android Studio as below :

  class MainClass{

    fun main(args: Array<String>)  {
        println("Hello World");
    }
 }

But, How can I run this kotlin class, and where the output will be generated.

scienticious
  • 438
  • 1
  • 7
  • 22
Jaimin Modi
  • 1,530
  • 4
  • 20
  • 72

2 Answers2

5

your main function has to be a top-level function. Try this:

fun main(args: Array<String>)  {
        println("Hello World");
    }

In order to run it, just click on green the icon next to the function name in AS.

Check out this screenshot

  • Top level means where in Activity ? inside onCreate() ? – Jaimin Modi Oct 09 '18 at 06:11
  • okay got it. But, it giving Exception in thread "main" java.lang.ClassNotFoundException: com.example.jaimin.kotinsetupdemo.MainClassKt at java.net.URLClassLoader.findClass(URLClassLoader.java:381) at java.lang.ClassLoader.loadClass(ClassLoader.java:424) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331) at java.lang.ClassLoader.loadClass(ClassLoader.java:357) at java.lang.Class.forName0(Native Method) at java.lang.Class.forName(Class.java:264) – Jaimin Modi Oct 09 '18 at 06:13
  • Create new kotlin file and then paste the above code, after that click the green play icon on the left side of function name.. You will get the output in your Run tab on the bottom left of the screen. – deaddroid Oct 09 '18 at 07:27
  • 1
    +1 @JaiminModi Only way I can work around it is by adding this to gradle file: `sourceSets { main { main.kotlin.srcDirs = ['src/main/java'] } }` and oddly, the gradle file needs to be re-synced for every run! – Conti Feb 03 '19 at 20:43
0

Use this code, You will see a run icon near function.

class Test {
        companion object {
            @JvmStatic
            fun main(args: Array<String>) {
                println("Hello test!")
            }
        }
    }
Yamini
  • 732
  • 7
  • 11