Get a Free Estimate!

5 min read

Category: Development

30 Aug 2022

30 Aug 2022

5 min read / Category: Development

How to quickly write and run Kotlin script - practical guide

Krzysztof Marczewski

Share

Facebook Twitter LinkedIn

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 kotlin

import java.io.File

fun 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.")
    }
}



About the Author

Krzysztof Marczewski is an Android Developer at Angry Nerds, focused on developing great code and constantly growing his tech skills. Delighted with Kotlin, Compose, and multiplatform. Non-fiction bookworm who loves minimal UI, smart UX, and clever copywriting. He writes his development-related blog - https://selfformat.com/.

Krzysztof Marczewski

Share

Facebook Twitter LinkedIn
comments powered by Disqus
Let's get in touch!

Let’s get in touch!

Contact us today to receive a free quote for your app or project.

Get a Free Estimate! Arrow right