在Android Studio中运行具有主要功能的单个Kotlin类 [英] Run single kotlin class with main function in android studio

查看:819
本文介绍了在Android Studio中运行具有主要功能的单个Kotlin类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试熟悉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.

我仅使用main方法在我的android项目中创建了一个名为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在主要方法的左侧向我显示了一个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)调试维护

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.

推荐答案

更新:

方法1:

现在您可以使用空的main()方法创建一个kotlin文件,然后可以使用android studio( AS版本:3.5.3 )中的左侧(第7行)中的运行图标直接运行代码>)之类的

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

这将使用PSVM方法(和所需的结构)在内部创建TestKt(文件名)class来执行代码.

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

  1. 在项目导航面板中选择Project视图.
  2. New -> Scratch File -> Kotlin创建Kotlin暂存文件
  3. 现在添加您的代码,并在右侧面板上查看结果

  1. Select the Project view in the project navigation panel.
  2. Create a Kotlin scratch file from New -> Scratch File -> Kotlin
  3. Now add your code and see the result on the right-side panel

Android Studio(intellij)提供了REPL(实时评估打印循环)工具来编写和执行kotlin代码.

Android studio (intellij) provides REPL(Real Eval Print Loop) tool to write and execute kotlin code.

  1. 将kotlin REPL打开为Tool -> kotlin -> kotlin REPL

  1. 编写代码

  1. 按Command + Enter(在Mac上)执行代码(请注意不同平台上的按键组合)

编写代码或import

提示:

  • 更改源代码后重新构建项目
  • 使用箭头键返回历史记录

这篇关于在Android Studio中运行具有主要功能的单个Kotlin类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆