HelloCW
HelloCW

Reputation: 2325

How can I run the console code of Kotlin in Android Studio?

I'm learning Coroutines of Kotlin, many sample codes such as Code A run under console.

At present I have to test it online at https://play.kotlinlang.org/, it's too slow.

How can I run theses codes in Android Studio?

Code 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()
} 

Added Content

Thanks!

But I can't get result when I run the code, I only get the information "fun main(): Unit"!

Image A enter image description here

Upvotes: 0

Views: 2204

Answers (1)

Yann Huissoud
Yann Huissoud

Reputation: 1033

I would personally use a scratch file File > New > Scratch File (mac shortcut Cmd ⌘ Shift N) type kotlin.

enter image description here

Upvotes: 5

Related Questions