在android studio中使用main函数运行单个kotlin类 [英] Run single kotlin class with main function in android studio
问题描述
我正在尝试熟悉 Kotlin,以便在我的 Android 应用程序中使用.所以首先我想尝试一些简单的 kotlin 示例,只是为了熟悉 kotlin 的语法.
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.
我在我的 android 项目中使用 main 方法创建了一个名为 Main.kt
的类.
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 在 main 方法的左侧向我展示了一个 kotlin 图标,当我点击这个图标时,它向我展示了以下三个选项:
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) 运行 Mainkt
1) Run Mainkt
2) 调试 Mainkt
2) Debug Mainkt
3) 在覆盖范围内运行 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.
推荐答案
更新:
方法一:
现在您可以使用空的 main()
方法创建一个 kotlin 文件,然后您可以使用 android studio(AS 版本)左侧(第 7 行)的运行图标直接运行代码: 3.5.3 ) 编辑器喜欢
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
这将在内部创建 TestKt(文件名)class
和 PSVM
方法(和所需的结构)来执行代码.
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
方法 2(使用 Scratch 文件,在 AS 3.6 上测试):
Approach 2(with Scratch file, tested on AS 3.6):
- 在项目导航面板中选择
Project
视图. - 从
New -> 创建 Kotlin 暂存文件暂存文件 ->科特林
- 现在添加您的代码并在右侧面板上查看结果
Android studio (intellij) 提供 REPL(Real Eval Print Loop)工具来编写和执行 kotlin 代码.
Android studio (intellij) provides REPL(Real Eval Print Loop) tool to write and execute kotlin code.
- 打开 kotlin REPL 作为
Tool ->科特林->kotlin REPL
- 编写代码
- 按 command + enter(在 Mac 上)执行您的代码(注意不同平台上的组合键)
要么写代码要么导入
类
提示:
- 更改源代码后重新构建项目
- 使用箭头键返回历史
这篇关于在android studio中使用main函数运行单个kotlin类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!