• ABOUT
  • NEWSLETTER
  • Contact
Krzysztof Marczewski Krzysztof Marczewski
  • ABOUT
  • NEWSLETTER
  • Contact
  • Productivity

How to quickly write and run Kotlin script – practical guide

  • Krzysztof Marczewski
  • 15 September 2022
  • 2 minute read

Not so long ago at Angry Nerds 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.kts — remember 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.")
    }
}
Total
0
Shares
0
0
0
0
Previous Article
  • Productivity

YearCompass – fix your New Year’s resolutions

  • Krzysztof Marczewski
  • 29 December 2021
View Post
Next Article
  • Development

How to change git history with git-filter-repo

  • Krzysztof Marczewski
  • 26 February 2025
View Post

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

© 2024 by Krzysztof Marczewski

Input your search keywords and press Enter.

We use cookies on our website to give you the most relevant experience by remembering your preferences and repeat visits. By clicking “Accept”, you consent to the use of ALL the cookies.
Cookie settingsACCEPT
Manage consent

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.
Necessary
Always Enabled
Necessary cookies are absolutely essential for the website to function properly. These cookies ensure basic functionalities and security features of the website, anonymously.
CookieDurationDescription
cookielawinfo-checbox-analytics11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Analytics".
cookielawinfo-checbox-functional11 monthsThe cookie is set by GDPR cookie consent to record the user consent for the cookies in the category "Functional".
cookielawinfo-checbox-others11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Other.
cookielawinfo-checkbox-necessary11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookies is used to store the user consent for the cookies in the category "Necessary".
cookielawinfo-checkbox-performance11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Performance".
viewed_cookie_policy11 monthsThe cookie is set by the GDPR Cookie Consent plugin and is used to store whether or not user has consented to the use of cookies. It does not store any personal data.
Functional
Functional cookies help to perform certain functionalities like sharing the content of the website on social media platforms, collect feedbacks, and other third-party features.
Performance
Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.
Analytics
Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics the number of visitors, bounce rate, traffic source, etc.
Advertisement
Advertisement cookies are used to provide visitors with relevant ads and marketing campaigns. These cookies track visitors across websites and collect information to provide customized ads.
Others
Other uncategorized cookies are those that are being analyzed and have not been classified into a category as yet.
SAVE & ACCEPT