kotlinx.coroutines 基本示例无法识别 GlobalScope.launch 提供的 CoroutineScope

kotlinx.coroutines basic example can't recognise CoroutineScope provided by GlobalScope.launch

我已经尝试 运行 https://github.com/Kotlin/kotlinx.coroutines/blob/master/docs/basics.md#your-first-coroutine 使用最新库版本的示例,但我在 'delay' 函数中遇到错误,告诉我:

Suspend function 'delay' should be called only from a coroutine or another suspend function

当我运行代码出现这个错误:

Exception in thread "main" java.lang.NoClassDefFoundError: kotlin/coroutines/jvm/internal/CoroutineImpl
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:763)
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
    at java.net.URLClassLoader.defineClass(URLClassLoader.java:467)
    at java.net.URLClassLoader.access0(URLClassLoader.java:73)
    at java.net.URLClassLoader.run(URLClassLoader.java:368)
    at java.net.URLClassLoader.run(URLClassLoader.java:362)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:361)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:349)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at com.example.MainKt.main(Main.kt:6)
Caused by: java.lang.ClassNotFoundException: kotlin.coroutines.jvm.internal.CoroutineImpl
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:349)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 13 more

这是我的 gradle 配置:

buildscript {
    ext.kotlin_version = '1.3.0'
    repositories {
        jcenter()
    }
    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}

apply plugin: 'kotlin'

kotlin {
    experimental {
        coroutines 'enable'
    }
}

repositories {
    jcenter()
}

dependencies {
    compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
    compile "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.0.0"
}

示例中的代码:

package com.example

import kotlinx.coroutines.*

fun main(args: Array<String>) {
  GlobalScope.launch { // launch new coroutine in background and continue
    delay(1000L) // non-blocking delay for 1 second (default time unit is ms)
    println("World!") // print after delay
  }
  println("Hello,") // main thread continues while coroutine is delayed
  Thread.sleep(2000L) // block main thread for 2 seconds to keep JVM alive
}

更新 IDEA kotlin 插件到 1.3 并重启 IDEA

https://github.com/Kotlin/kotlinx.coroutines/issues/766