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

early 2020ies kscript that you find at https://github.com/holgerbrandl/kscript seems to be the most convenient and well supported way to go ...


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


KtsRunner

I've published a simple library that let's you run scripts from regular Kotlin programs.

https://github.com/s1monw1/KtsRunner

Example

  1. The example class

    data class ClassFromScript(val x: String)
    
  2. The .kts file

    import de.swirtz.ktsrunner.objectloader.ClassFromScript
    
    ClassFromScript("I was created in kts")
    
  3. The code to load the class

    val scriptReader =  Files.newBufferedReader(Paths.get("path/classDeclaration.kts"))
    val loadedObj: ClassFromScript = KtsObjectLoader().load<ClassFromScript>(scriptReader)
    println(loadedObj.x) // >> I was created in kts
    

As shown, the KtsObjectLoader class can be used for executing a .kts script and return its result. The example shows a script that creates an instance of the ClassFromScript type that is loaded via KtsObjectLoader and then processed in the regular program.


As of 2020 (Kotlin 1.3.70), you can just use the straightforward

kotlin script.main.kts

Note that using the file extension .main.kts instead of .kts seems to be important.

Note that for me this does not seem to run the main() function if defined, I had to add a manual call to main() at the top level.

One of the advantages of Kotlin script is the ability to declare code and dependencies inside a single file (with @file:DependsOn, see for example here)

Tags:

Java

Kotlin