Discovering an experimental gem and its capabilities
What is Kotlin Script API?
Is an experimental API from Kotlin that allows you to run Kotlin code in a script-like manner; it compiles on the fly, uses a build tool under the hood, and you need minimal configuration inside the file to work.
There are different flavours of Kotlin Scripts, I will be focusing on the “main.kts” variant.
Key Features
- Standalone: You can run your Kotlin code directly from a script without any additional setup like Maven or Gradle.
- Simplicity: You don’t need a main class or main function to run it, write your procedural code and execute it.
- Interoperability: It allows the usage of Java and Kotlin standard library functions and additional dependencies.
- Not all features are available: Not all Kotlin features are supported in script mode, and it is not known if those will be available in the future.
How do I create those scripts?
Let me show you some examples:
Basic hello world
|
|
Hello World with arguments and a dependency
|
|
Hello World with args with complex configuration
|
|
As you can see, there is no class in the code, and no main function is just procedural. Internally auto-generates the main method but is invisible to the developer.
How can I run the scripts I created?
Install Kotlin compiler
You need kotlin compiler installed in your system:
- Linux: On most linux distributions you can install it as “kotlin” using your package manager.
- Windows: download kotlin-compiler from Github releases , unzipped and add “bin” folder, where the “kotlinc.bat” is located, to your user or system PATH and then restart your terminal.
- Mac: I have no idea? maybe brew?
Run your script
Once you finished installing the kotlin compiler, if you are on Linux/Mac you have to make sure you have set the shebang correctly #!/usr/bin/env kotlin
on the first line of your file.
Run the script using the following command depending on your OS/Terminal:
Linux/Mac:
./my-script.main.kts
Windows CMD:
kotlinc.bat -script my-script.main.kts
Windows Powershell:
.\kotlinc.bat -script my-script.main.kts
Additional info
I started saying this is a specific variant of the script API, the others are:
- Kotlin Basic scripts (.kts instead of .main.kts): for simple scripts, has no support for dependencies.
- Kotlin Jupyter (Interactive Notebooks) : This is not part of Script API but works in similar ways.
Script API has the ability act as a host to execute those scripts to use inside existing applications .
Stay up to date
You can see updates related to Script API in this ticket, at the time of writing, the improvements are slow but are moving: https://youtrack.jetbrains.com/issue/KT-49511
Thanks for reading!
Namaste.