3

Is it possible to import classes from kotlinx package in a simple Kotlin script?

myscript.kts:

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

println("")

Running the above script with kotlinc -script myscript.kts gives this error:

error: unresolved reference: kotlinx

When I checked kotlinc/lib/ directory, there exists kotlinx-coroutines-core.jar and so on.
I am using Kotlin compiler version 1.4.0.

Mahozad
  • 18,032
  • 13
  • 118
  • 133
  • You can use `@file:DependsOn()` and `@file:Repository()` to add dependency and repos, but I have no idea to use serialization as it is mainly a compiler plugin, and generates stubs on build, I guess that is not really possible. – Animesh Sahu Jan 12 '21 at 13:21

2 Answers2

1

You can execute kotlin like a simple bash script with dependencies if you change the name to *.main.kts

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
Yuri Schimke
  • 12,435
  • 3
  • 35
  • 69
0

First of, the imports you have are related to the kotlin serialization library not the coroutines one. As for running your script you need to specify the dependencies to the compiler. You can run your script like this :

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

I've used the old kotlin serialization runtime but you'll need to adapt the command to your needs.

bcordier
  • 451
  • 2
  • 4