Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

kotlin

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?

like image 733
Jire Avatar asked Jan 24 '16 09:01

Jire


People also ask

How do I open a .KTS file?

It contains executable Kotlin source code. KTS files can be opened and edited in any text editor, and they can be executed using the Kotlin compiler (kotlinc). Kotlin is a statically-typed programming language developed by JetBrains.


2 Answers

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

like image 71
Alexander Udalov Avatar answered Oct 02 '22 15:10

Alexander Udalov


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.

like image 35
s1m0nw1 Avatar answered Oct 02 '22 15:10

s1m0nw1