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?
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.
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 ...":
I've published a simple library that let's you run scripts from regular Kotlin programs.
https://github.com/s1monw1/KtsRunner
The example class
data class ClassFromScript(val x: String)
The .kts
file
import de.swirtz.ktsrunner.objectloader.ClassFromScript ClassFromScript("I was created in kts")
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With