Kotlin - Baby Steps

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).

[

](https://kotlinlang.org/

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.

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

And, run this.

1$ chmod a+x ./list_folders.kts
2$ ./list_folders.kts .
3./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.

comments powered by Disqus