How can I run Kotlin-Script (.kts) files from with

2019-04-03 04:53发布

问题:

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?

回答1:

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 ...":



回答2:

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.



标签: java kotlin