How to quickly write and run Kotlin script — practical guide

Krzysztof Marczewski
Self Format
Published in
3 min readSep 15, 2022

--

Not so long ago we had a test that involved a large address book with several thousands of contacts. In order to have such an extensive collection, we came up with the need to generate vCard file with random contacts.

Recently, we completed a test with a large address book containing thousands of contacts. To have such a vast collection, we needed to generate a vCard file with random contacts.​

The easiest way to execute Kotlin code quickly in Android Studio project is by creating an empty Kotlin file, and typing psvm to auto-generate main function (or psvma for one with args). Inside it, we can write our Kotlin code. Last step is to click the green run button next to the main and viola — code is executed with the output presented.​

Since parameters should always be given via altering configuration in the “Program Arguments” area, it is not a simple or easily reproducible setup from my perspective.​

I came to the conclusion that it will be easier to have it in the form of an executable script from the command line. As Kotlin has that ability with .kts (Kotlin script) files, I started looking for ways to achieve it in the fastest and simplest way possible.

Following is the summary of my discoveries:

Setup

• What you need is kotlin compiler in order to run our script from command line.

brew update
brew install kotlin

• As I’m using mac and brew, this command was the simplest to get, but if you have a different hardware/software setup, use these instructions.

• Text editor — I’ve just used Android Studio, but anything that understands Kotlin will be enough.

Script

There are several ways of creating and running scripts with Kotlin. The easiest one to use is called Kotlin-main-kts.

Let’s create the easiest hello-world script with it:

• create file with .main.kts extension e.g. helloworld.main.kts

• add “header” as a first line to indicate it should be our Kotlin script

#!/usr/bin/env kotlin

• below it insert your script content e.g. println("Hello world.")

• make your file executable with chmod +x helloworld.main.kts

• now you can run your script with standard command of running executable files ./hellowrold.main.ktsremember that in order to run it, other people will also need to install Kotlin compiler

Arguments

Arguments are accessible right away by calling args e.g. args[0]

No main function needed as we’re inside of it. So all code is wrote top-level like.

if (args.size != 2) {
println("Please specify exactly 2 arguments in this example")
} else {
println("Your arguments are: ${args[0]}, ${args[1]}")
}

Now run it with: ./helloworld.main.kts “Hello” “World”

Which is equivalent to: kotlinc -script helloworld.main.kts "Hello" "World"

That’s it — quick and easy to use or run.

For a curious real-life yet very basic example here’s our vCard file generating script:

#!/usr/bin/env kotlinimport java.io.Filefun generateVCard(numberOfContacts: Int): String {
val vCard: StringBuilder = StringBuilder()
(1..numberOfContacts).forEach { number ->
vCard.append(
"""
BEGIN:VCARD
VERSION:3.0
PRODID:-//Apple Inc.//macOS 12.4//EN
N:Surname$number;Name$number;;;
FN:Name$number Surname$number
TEL;type=CELL;type=VOICE;type=pref:+48 101 000 $number
END:VCARD
""".trimIndent()
)
}
return vCard.toString()
}
if (args.size != 1) {
println("No argument. Please specify number and try again")
} else {
val numberOfContacts = args[0].toIntOrNull()
if (numberOfContacts == null) {
println("Specified number is not Integer, please try again")
} else {
println("Executing script")
val vCard = generateVCard(numberOfContacts) File("contacts$numberOfContacts.vcf").writeText(vCard) println("Generating vCard completed.")
}
}

Self format

Thanks for reading — I hope you’ve learned something new. As I’m publishing content in many places about different things, so it’s good to visit self.format where you can find all destinations.

self.format is something I’m creating. It’s a blog about mobile development. It’s a newsletter about self-development. It’s also tweets and stories with handy tools and inspiring content.

See you there!

--

--

Krzysztof Marczewski
Self Format

📱 Mobile dev focused on how to develop great code and yourself as a coder. 💡 Providing continuous self-development ideas on: http://bio.link/selfformat