首页 > 解决方案 > 如何在 Android Studio 中运行 Kotlin 的控制台代码?

问题描述

我正在学习 Kotlin 的 Coroutines,许多示例代码如 Code A 在控制台下运行。

目前我必须在https://play.kotlinlang.org/上在线测试它,它太慢了。

如何在 Android Studio 中运行这些代码?

代码 A

import kotlinx.coroutines.*

fun main()=runBlocking{
     val job = launch {
       val child = launch {
         try {
            delay(Long.MAX_VALUE)
         } finally {
            println("1. Child is cancelled")
         }
     }

      yield()
      println("2. Cancelling child")

      child.cancel()
      child.join()

      yield()
      println("3. Parent is not cancelled")
    }
    job.join()
} 

添加内容

谢谢!

但是当我运行代码时无法得到结果,我只得到信息“fun main(): Unit”!

图像 A 在此处输入图像描述

标签: android-studiokotlin

解决方案


我个人会使用暂存文件File > New > Scratch File (Type Kotlin)

在此处输入图像描述


推荐阅读