kotlinx.coroutines基本示例无法识别GlobalScope.launch

时间:2018-11-07 01:36:01

标签: kotlin kotlinx.coroutines

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

  

只能从协程或其他暂停函数调用暂停函数“ delay”

运行代码时,出现此错误:

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.access$100(URLClassLoader.java:73)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:368)
    at java.net.URLClassLoader$1.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
}

1 个答案:

答案 0 :(得分:1)

将IDEA kotlin插件更新为1.3,然后重新启动IDEA

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