3

How can I run kotlin script from command line? Without maven, gradle or kotlin-DSL-gradle, only command line options.

I have two kotlin files in the play folder

user.kt

data class User(val name: String)

play.kts

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

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?

1 Answer 1

3

In scripting mode there is nothing that links those two files together, so the compiler has no way of knowing where to find the User class, since by default it is just parsing the play.kts file.

You have a couple of options to achieve what you want:

  1. Rename your play script to play.main.kts, rename user.kt to user.kts, add @file:Import("user.kts") to the top of the play script and now run it with your first attempted command

  2. Compile the user.kt file (note it's not a kts, so it needs to be compiled to be usable) with kotlinc user.kt, this will compile it to user.class in the current dir, and then add the current dir to the classpath of the script runner: kotlinc -cp . -script play.kts

The first is probably the most versatile, it also allow you to add remote dependencies with @file:DependsOn(<gradle-style-dep>). All of that only works if the filename ends in .main.kts though.

Note that you still need to execute that main function in your script in order to do anything, so add main() below what you have.

You can puzzle this information and more together on your own using https://github.com/Kotlin/KEEP/blob/master/proposals/scripting-support.md , but imo this is all pretty badly documented (although it works well)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.