Run a single .kt file in Android Studio

…衆ロ難τιáo~ 提交于 2021-01-27 07:22:13

问题


I created a Scratch Kotlin file in Android Studio. I simply want to run this scratch.kt file and get output.

I fiddled with Run Cofigurations but cannot understand what will go into Main Class.


回答1:


If you create a top-level function called main in any kotlin file, a green run button will appear next to it that allows you to run it as a program:

Note that this works in Android Studio as well as in IntelliJ IDEA.




回答2:


You can create a scratch kotlin file with File -> New -> Scratch File -> Kotlin. With this you should be able to create and run kotlin script files to try features, code and so on.

If your intention is to create a full standlone kotlin project. My recomendation is to use IntelliJ IDEA. Doing so with Android Studio may be possible but you won't stop facing issues and having to search for workarounds all the time.




回答3:


Use this code, You will see a run icon near function.

class Test {
    companion object {
        @JvmStatic
        fun main(args: Array<String>) {
            println("Hello test!")
        }
    }
}



回答4:


Android Studio allow to run Kotlin code, but the green triangle (to Run) appears just if you don't use a class file or if you add a fun main(args: Array<String>){} out of the class's brackets. So, the way I am doing this (in AS 4.0) is:

  1. Creating a Kotlin FILE (not choose a CLASS) and putting inside just:

    fun main(args: Array) {}

  2. Then, inside this method you are allowed to use Kotlin classes. You can do for example:

    fun main(args: Array){ var oneMan: Man = Man() oneMan.method() }

being Man a regular Kotlin class.



来源:https://stackoverflow.com/questions/54217696/run-a-single-kt-file-in-android-studio

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