Run single kotlin class with main function in android studio

AndroidAndroid StudioKotlinMain

Android Problem Overview


I am trying to get familiar with Kotlin to use in my android apps. So first I want to try out some simple kotlin examples, just to get familiar with syntax of kotlin.

I made a class named Main.kt in my android project with just main method.

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

Android studio shows me a kotlin icon to left of main method and when I click on this icon, It shows me below three option:

  1. Run Mainkt

  2. Debug Mainkt

  3. Run Mainkt with coverage

I chose first one but it throws me

Exception in thread "main" java.lang.ClassNotFoundException: com.vikalp.kotlin.MainKt
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)
at com.intellij.rt.execution.application.AppMainV2.main(AppMainV2.java:107)

I am stuck with such a small problem. Let me know if anyone of you have faced problem like this and what is the solution.

Android Solutions


Solution 1 - Android

Update:

Approach 1:

Now you can create a kotlin file with empty main() method and then you can run the code directly using run icon on left(of 7th line) in android studio (AS version: 3.5.3 ) editor like

enter image description here

This will internally create the TestKt(name of file) class with PSVM method(and required structure) to execute the code.

Demo configuration(automatically generated) to run this file will look like

enter image description here

Approach 2(with Scratch file, tested on AS 3.6):

  1. Select the Project view in the project navigation panel.
  2. Create a Kotlin scratch file from New -> Scratch File -> Kotlin enter image description here
  3. Now add your code and see the result on the right-side panel enter image description here

Android studio (intellij) provides REPL(Real Eval Print Loop) tool to write and execute kotlin code.

  1. Open kotlin REPL as Tool -> kotlin -> kotlin REPL

enter image description here

  1. Write your code

enter image description here

  1. Press command + enter (on mac) to execute your code(pay attention to the key combo on different platform)

Either write code or import the class

enter image description here

Tips:

  • Rebuilt the project once you change the source code

  • Use arrow key to go back in history

Solution 2 - Android

class Main {
companion object {
    @JvmStatic fun main(args: Array<String>) {
        println("Hello!")
    }
}

or Just create a configuration with the main class as "MainKt".

enter image description here

Solution 3 - Android

To Run single kotlin class with main function in android studio,

You need to,

  • First create a New Project with any Template
  • Then create a kotlin file with any name
  • Then write the main function as showing in below screenshot:

(Tested in Android Studio Arctic Fox | 2020.3.1)

enter image description here

Solution 4 - Android

As mentioned in the issue tracker, a temporary workaround is to add the following to the root build.gradle script:

subprojects { subProject ->
    afterEvaluate {
        if (subProject.plugins.hasPlugin("kotlin") && subProject.plugins.hasPlugin("java-library")) {
            subProject.kotlin.copyClassesToJavaOutput = true
            subProject.jar.duplicatesStrategy = DuplicatesStrategy.EXCLUDE
        }
    }
}

See: https://issuetracker.google.com/issues/68021152#comment12

Solution 5 - Android

just writer open function without class definition you will get green button option to run your code.No extra code needed.

Like this :-

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

Solution 6 - Android

You can create a new Java library module where you can run non-Android projects, see this answer for instructions. This is a Java related question, but it should work all the same with Kotlin main functions too. Edit: I can't get this working right now.

You could also use IntelliJ IDEA instead which is a Java/Kotlin/etc. IDE instead of an Android one, the community edition is free and supports Kotlin.

If you just need to run really simple code, you can also do it online here: https://try.kotlinlang.org/

Solution 7 - Android

In my Android Studio, simply open the Kotlin file with your main function, then to the left of the main function there's a green "Run" triangle. Just click on that one to run this file.

Solution 8 - Android

This is simply not possible as of now in Android Studio 3.0.

There is a bug filed for this already: https://issuetracker.google.com/issues/68021152

Solution 9 - Android

I faced the same problem and a workaround is run your code in a test class under test folder, then right-click on Run {your test class}

It is enough if you only want to play with Kotlin.

Solution 10 - Android

Maybe this method worked use gradle-3.3, at lease it worked for me.

Solution 11 - Android

Tested on Android Studio 3.1.3

Note that this is an edited version of my other answer.

Using this method you can have Java/Kotlin modules and Android modules in the same project and also have the ability to compile and run Java/Kotlin modules as stand alone projects.

  1. Open your Android project in Android Studio. If you do not have one, create one.

  2. Click File > New Module. Select Java Library and click Next.

  3. Fill in the package name, etc and click Finish. You should now see a Java module inside your Android project.

  4. Add your Java/Kotlin code to the Java module you've just created.

  5. Click on the drop down to the left of the run button. Click Edit Configurations...

  6. In the new window, click on the plus sign at the top left of the window and select Application

  7. A new application configuration should appear, enter in the details such as your main class and classpath of your module.

  8. Click OK.

  9. Next we need to add the Kotlin plugin. Add the following code to your project level build.gradle (lines to add are denoted by >>>):

     buildscript {
     	>>> ext.kotlin_version = '1.2.51'
     	repositories {
     		google()
     		jcenter()
     	}
     	dependencies {
     		classpath 'com.android.tools.build:gradle:3.1.3'
     		>>> classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    
     		// NOTE: Do not place your application dependencies here; they belong
     		// in the individual module build.gradle files
     	}
     }
     ...
    
  10. Add the following code to your module level build.gradle (lines to add are denoted by >>>):

     apply plugin: 'java-library'
     >>> apply plugin: 'kotlin'
    
     dependencies {
     	implementation fileTree(dir: 'libs', include: ['*.jar'])
     	>>> implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
     	>>> runtimeClasspath files(compileKotlin.destinationDir)
     }
     ...
    

Now if you click run, this should compile and run your Java/Kotlin module.

If you get the error Error: Could not find or load main class..., just enter your main class (as you've done in step 7) again even if the field is already filled in. Click Apply and then click Ok.

Solution 12 - Android

It is supported now (V 3.2.1 )

I just finished upgrading my Android studio, created A new project I then waited until all the building finished ( if you are advised to upgrade something please accept )

After that I created a new Kotlin file and added your code, right click and choose the Run option and that's it .

I can see the following in the console

> Hello World > > Process finished with exit code 0

Solution 13 - Android

It is pretty easy. I saw posts regarding that and can't quickly follow up. The only difference you need to make is to change the configuration. Because you want to update your app compilation to kotlin class compilation. Create any Kotlin File/Class in any folder. Set Deploy options under Edit Configurations of Android app as Deploy "Nothing" and Launch value as "Nothing".

enter image description here

Solution 14 - Android

In my case I add these:

  1. Add this apply plugin: 'kotlin-android'

  2. And also

dependencies {
    classpath 'org.jetbrains.kotlin:kotlin-gradle-plugin:$your-version' 
}

This fixes the problem.

Solution 15 - Android

The easiest way is to create a new Java library module like this, and configure it for Kotlin.

You also have to add this in your build.gradle of the imported module:

dependencies {
    runtimeClasspath files(compileKotlin.destinationDir)
}

Solution 16 - Android

  1. Create default project with gradle > gradle init -> kotlin-application

  2. Import project into Android Studio

  3. Create new 'run configuration' with 'Application' template and set 'app.AppKt' as a 'Main class' (see build.gradel->mainClassName). enter image description here

  4. Run! enter image description here

Solution 17 - Android

A less time consuming way would be, configure Android Studio to run Java Program and then call your Kotlin Class from that main method:

public class JavaApplication{
  public static void main(String[] args){
     KotlinApplicationKt.main(new String[]{});
  }
}

To configure your android studio to run Java Application:

  1. Just add a new configuration(Run Menu > Edit Configurations > + icon )
  2. Select Application & then configure your Main class to your JavaApplication.class
  3. Set the working directory to your project directory & JRE as JDK
  4. Apply and Run !

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionVikalpView Question on Stackoverflow
Solution 1 - AndroidPavneet_SinghView Answer on Stackoverflow
Solution 2 - AndroidMaxim FirsoffView Answer on Stackoverflow
Solution 3 - AndroidDevenView Answer on Stackoverflow
Solution 4 - AndroidJared RummlerView Answer on Stackoverflow
Solution 5 - Androidshadab sheikhView Answer on Stackoverflow
Solution 6 - Androidzsmb13View Answer on Stackoverflow
Solution 7 - AndroidPeppe L-GView Answer on Stackoverflow
Solution 8 - AndroidHenryView Answer on Stackoverflow
Solution 9 - AndroidMiguel GarciaView Answer on Stackoverflow
Solution 10 - AndroidxwangView Answer on Stackoverflow
Solution 11 - AndroididunnololzView Answer on Stackoverflow
Solution 12 - AndroidA.AlqadomiView Answer on Stackoverflow
Solution 13 - AndroidIshtdeep HoraView Answer on Stackoverflow
Solution 14 - AndroidKenanView Answer on Stackoverflow
Solution 15 - AndroidShahzad AkramView Answer on Stackoverflow
Solution 16 - AndroidDmitryView Answer on Stackoverflow
Solution 17 - AndroidPrathamesh sawantView Answer on Stackoverflow