74

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.

2

18 Answers 18

64

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
5
  • @JaiminModi make sure to rebuilt the project, or the import of your class is added in REPL before use. If there an error "build the app .." then click the build and it should work, I tested and it's running Commented Oct 9, 2018 at 21:38
  • How do you import a class created in the REPL into the app project?
    – Phil
    Commented Mar 15, 2019 at 5:24
  • 1
    @Phil we can import a class in REPL but we cannot do the reverse, since REPL code is temporary so cannot be used as part of the project though you can create a new file in project and copy paste the code there then use it. Commented Mar 27, 2019 at 19:13
  • Hello Pavneet I have followed approach one thanks it's working nicely.. My output is Demo(name=Aditi Deshpande) why Demo (name = ) ? Why it's not coming only my name? I am new to Kotlin programming language.. Can you please explain this?
    – AdiAtAnd
    Commented Aug 16, 2020 at 11:38
  • val print1 = Demo("Aditi Deshpande") println(print1.name) is giving me only Aditi Deshpande . Got it.. :)
    – AdiAtAnd
    Commented Aug 16, 2020 at 16:32
17
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

2
  • 2
    This doesn't answer the question. The question was how to do this in android studio and you are clearly using intelliJ.
    – SethCoast
    Commented Aug 9, 2018 at 16:00
  • 3
    it is now part of Android Studio 3.5
    – Gabor
    Commented May 17, 2019 at 0:58
11

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

8

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!")
}
2
  • this is easiest way to run kotlin class Commented Oct 23, 2021 at 7:12
  • Error: Could not find or load main class ..xxxxx.. Caused by: java.lang.ClassNotFoundException: ..xxxxxx...
    – Abhi
    Commented Jul 13, 2022 at 4:54
3

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

2

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/

9
  • 3
    Thanks @zsmb13...I dont want to use a separate IDE just to run a silly main function...but I will give it a try by adding java library module.
    – Vikalp
    Commented Jun 29, 2017 at 10:58
  • I suppose this editor try.kotlinlang.org does not give a much freedom. What If I want to create dependency b/w multiple java classes?
    – Vikalp
    Commented Jun 29, 2017 at 11:07
  • Tried using Java library module. NOT WORKING...Error: Could not find or load main class com.vikalp.kotlin.MainKt
    – Vikalp
    Commented Jun 29, 2017 at 11:15
  • You're right, I can't seem to get it working either, although I'm facing different problems.
    – zsmb13
    Commented Jun 29, 2017 at 11:50
  • Is your Main.kt in fololowing format: package xyz fun main(args : Array<String>) { println("Hi") } Commented Jun 29, 2017 at 12:00
2

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.

1

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

1

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.

1

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

1

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.

1

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

1

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

1

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.

0

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)
}
2
  • Please don't post images of code. Copy them into your answer and use the {} button to format them as code like you did with the build.gradle component. Commented Jul 8, 2018 at 18:34
  • The intention of posting this image is not to show the code. This is posted to show the scenario. Commented Jul 8, 2018 at 18:52
0
  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

0

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 !

-1
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        main()
    }

    fun main() {
        println("Hello, world!")
        // Hello, world!
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.