I was at Kotlin SG Meetup tonight. It had a lot of content. I will post more about that later.

On my way back home (now), I started reading Kotlin website about various features (here).

Kotlin

I was curious about command line usage of Kotlin. How will I complile kotlin classes outside an IDE? How to run this? What about the runtime libraries? etc.

It turns out to be very straight forward. No surprises.

  1. Just write your code in a .kt file
  2. Run kotlin compiler
    a. For Apps, use -include-runtime flag
    b. For libraries, DON’T include runtime
  3. Run app with java

But I want moar

I have Kotlin installed via SDKMAN. So, on the “Command Line” Tutorial page I saw (here) how to run kotlin as a script. Cool!

Now, I was more curious. I wanted to see if I could do one better. Can I write a script and execute it directly by filename? Lets try. Created a file list_folders.kts, as below.

list_folders.kts
1
2
3
4
5
#!/usr/bin/env kotlinc -script
import java.io.File
val folders = File(args[0]).listFiles { file -> file.isDirectory() }
folders?.forEach { folder -> println(folder) }

And, run this.

1
2
3
$ chmod a+x ./list_folders.kts
$ ./list_folders.kts .
./kotlin-koans

Wow! that worked. Trick is in the first line

1
#!/usr/bin/env kotlinc -script

This causes shell the use kotlinc interpreter for this script.