Run single kotlin class with main function in android studio
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.
Solution 1:
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:
class Main {
companion object {
@JvmStatic fun main(args: Array<String>) {
println("Hello!")
}
}
or Just create a configuration with the main class as "MainKt".