How to run kotlin script from command line?

How can I run kotlin script from command line?

I’m using it for some data processing (like python) and would like to keep things simple and avoid heavy machinery like maven, or gradle, only command line options.

There are two kotlin files in the play folder


data class User(val name: String)


fun main() {
  val user = User("Jim")
  println("Hello ${}")

It doesn’t work

kotlinc -script play.kts
error: unresolved reference: User (play.kts:4:14)
play.kts:4:14: error: unresolved reference: User
  val user = User("Jim")

But if I rename it to play.kt and run with command below it works.

kotlinc . -include-runtime -d play.jar && java -jar play.jar

Why it is so, and how to make it work?


Ideally, would be best to avoid JAR and use incremental compilation with cache to speed it up, is it possible?


You need to use the @file:Include("...") annotation in play.kts to import user.kts. See the following StackOverflow response: kotlinc - Kotlin Script (.kts) - How to divide it into multiple files? - Stack Overflow

1 Like

Thanks. Although, the way it looks, I think it’s better to just avoid it. Kotlin Scripts looks like a broken way of using Plain Kotlin.

How do you figure? You can still import maven dependencies and run Kotlin code like you normally would, it’s just interpreted via the Kotlin compiler.

Sure, it’s not ideal for production applications but for quick scripts it’s great

1 Like