· kotlin til

How to run a Kotlin script

I was recently helping Tim get a Pinot data-loading Kotlin script working and it took me a while to figure out the best way to run it. In this blog post, I’ll share the solution we came up with.

But first things first, we need to install Kotlin if it’s not already installed. I used a library called SDKMAN6 for all things JVM, so I’m gonna run the following command:

sdk install kotlin

And now for the Kotlin script. Our script prints out a JSON document representing a person:

@file:DependsOn("com.google.code.gson:gson:2.8.6") (1)

import com.google.gson.Gson

data class Person(val name: String)
class Blog {
    companion object {
        fun main(args: Array<String>) {
                Gson().toJson(Person("Mark Needham"))

println("Script started")
println("Before main function call")
Blog.main(arrayOf()) (2)
println("After main function call")
1 Install GSON as a dependency
2 Run the Blog main class

After trying a few different approaches, I came kscript, a wrapper around kotlinc that takes care of compilation and dependency management for us. We can install it like this:

sdk install kscript

And then run our script:

kscript script.kts
[kscript] Resolving com.google.code.gson:gson:2.8.6...
Script started
Before main function call
{"name":"Mark Needham"}
After main function call

And that’s it!

  • LinkedIn
  • Tumblr
  • Reddit
  • Google+
  • Pinterest
  • Pocket