Run single kotlin class with main function in android studio
AndroidAndroid StudioKotlinMainAndroid 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:
-
Run Mainkt
-
Debug Mainkt
-
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
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
Approach 2(with Scratch file, tested on AS 3.6):
- Select the
Project
view in the project navigation panel. - Create a Kotlin scratch file from
New -> Scratch File -> Kotlin
- Now add your code and see the result on the right-side panel
Android studio (intellij) provides REPL(Real Eval Print Loop) tool to write and execute kotlin code.
- Open kotlin REPL as
Tool -> kotlin -> kotlin REPL
- Write your code
- 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
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".
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)
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.
-
Open your Android project in Android Studio. If you do not have one, create one.
-
Click File > New Module. Select Java Library and click Next.
-
Fill in the package name, etc and click Finish. You should now see a Java module inside your Android project.
-
Add your Java/Kotlin code to the Java module you've just created.
-
Click on the drop down to the left of the run button. Click Edit Configurations...
-
In the new window, click on the plus sign at the top left of the window and select Application
-
A new application configuration should appear, enter in the details such as your main class and classpath of your module.
-
Click OK.
-
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 } } ...
-
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".
Solution 14 - Android
In my case I add these:
-
Add this
apply plugin: 'kotlin-android'
-
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
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:
- Just add a new configuration(Run Menu > Edit Configurations > + icon )
- Select Application & then configure your Main class to your JavaApplication.class
- Set the working directory to your project directory & JRE as JDK
- Apply and Run !