【问题标题】:Can I use kotlinx classes in Kotlin scripts?我可以在 Kotlin 脚本中使用 kotlinx 类吗?
【发布时间】:2021-04-17 09:43:19
【问题描述】:

是否可以在简单的 Kotlin 脚本中从 kotlinx 包中导入类?

myscript.kts

import kotlinx.serialization.*
import kotlinx.serialization.json.*

println("")

使用kotlinc -script myscript.kts 运行上述脚本会出现此错误:

error: unresolved reference: kotlinx

当我检查kotlinc/lib/目录时,存在kotlinx-coroutines-core.jar等等。
我使用的是 Kotlin 编译器版本 1.4.0。

【问题讨论】:

  • 你可以使用@file:DependsOn()@file:Repository()来添加依赖和repos,但我不知道使用序列化,因为它主要是一个编译器插件,并在构建时生成存根,我猜是不太可能。

标签: kotlin kotlinx.serialization kotlin-script kotlinx


【解决方案1】:

如果将名称更改为 *.main.kts,则可以像执行带有依赖项的简单 bash 脚本一样执行 kotlin

https://raw.githubusercontent.com/yschimke/okurl-scripts/master/commands/tube-status.main.kts

$ ./tube-status.main.kts
Good Service
Good Service
Minor Delays
Part Closure
Minor Delays
Good Service
Minor Delays
Good Service
Part Closure
Good Service
Planned Closure

【讨论】:

    【解决方案2】:

    首先,您的导入与 kotlin 序列化库有关,而不是与协程有关。 至于运行脚本,您需要指定编译器的依赖项。你可以像这样运行你的脚本:

    kotlinc -script myscript.kts -classpath kotlinx-serialization-runtime-0.20.0-1.4.0-rc-95.jar
    

    我使用了旧的 kotlin 序列化运行时,但您需要根据需要调整命令。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-05
      • 1970-01-01
      • 2014-05-13
      • 2012-06-07
      • 2011-03-06
      • 2017-12-23
      • 2015-09-06
      • 1970-01-01
      相关资源
      最近更新 更多