Skip to content
Advertisement

How can I run Kotlin-Script (.kts) files from within Kotlin/Java?

I noticed that IntelliJ can parse .kts files as Kotlin and the code editor picks them up as free-floating Kotlin files. You are also able to run the script in IntelliJ as you would a Kotlin file with a main method. The script executes from top to bottom.

This form is PERFECT for the project I’m working on, if only I knew an easy way to use them from within Java or Kotlin.

What’s the idiomatic way to “run” these scripts from Java or Kotlin?

Advertisement

Answer

Note that script files support in Kotlin is still pretty much experimental. This is an undocumented feature which we’re still in the process of designing. What’s working today may change, break or disappear tomorrow.

That said, currently there are two ways to invoke a script. You can use the command line compiler:

kotlinc -script foo.kts <args>

Or you can invoke the script directly from IntelliJ IDEA, by right-clicking in the editor or in the project view on a .kts file and selecting “Run …”:

Run .kts from IntelliJ IDEA

Advertisement