Run single kotlin class with main function in android studio

后端 未结 15 661
后悔当初
后悔当初 2020-12-13 13:04

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.

<
相关标签:
15条回答
  • 2020-12-13 13:04

    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

    0 讨论(0)
  • 2020-12-13 13:04

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

    0 讨论(0)
  • 2020-12-13 13:05
    class Main {
    companion object {
        @JvmStatic fun main(args: Array<String>) {
            println("Hello!")
        }
    }
    

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

    0 讨论(0)
  • 2020-12-13 13:08

    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 !

    0 讨论(0)
  • 2020-12-13 13:11

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

    0 讨论(0)
  • 2020-12-13 13:12

    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/

    0 讨论(0)
提交回复
热议问题