Run single kotlin class with main function in android studio

丶灬走出姿态 提交于 2019-11-28 06:47:37

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

  1. Write your code

  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

Tips:

  • Rebuilt the project once you change the source code
  • Use arrow key to go back in history
class Main {
companion object {
    @JvmStatic fun main(args: Array<String>) {
        println("Hello!")
    }
}

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

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/

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

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

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.

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

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.

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)
}

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. 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).

  4. Run!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!