ToiletaPaper 142

Kotlin Scripts

Problem

Java and Kotlin are nice languages for software development, but for small scripts, you have so far probably used languages like Python or JavaScript. There is nothing wrong with these languages per se, but the syntax and standard libraries are different from JVM languages and I tend to use google a lot to write the scripts.

Solution

For writing scripts in Kotlin, you don't need Gradle build scripts, package.json or similar. You can directly specify the dependencies in the script file and then just write Kotlin code. The file must end in .main.kts and Intellij IDEA supports it natively. Below is a small script that queries the well-known Petstore API. To run it, you need to install Java and the Kotlin compiler. On Windows, you can download it from Github (kotlin-compiler-X.X.XX.zip) and then add the bin folder to the PATH. On Linux, you can use e.g. snap `sudo snap install --classic kotlin`, on Mac e.g. homebrew `brew install kotlin`.

Example

petstore.main.kts
@file:DependsOn("io.ktor:ktor-client-okhttp:+")
@file:DependsOn("io.ktor:ktor-client-gson:+")
import io.ktor.client.*
import io.ktor.client.features.json.*
import io.ktor.client.request.*
import kotlinx.coroutines.runBlocking

data class InventoryResponse(val sold: Int, val pending: Int, val available: Int)
val url = "https://petstore.swagger.io/v2/store/inventory"
HttpClient { install(JsonFeature) }.use { client ->
    runBlocking {
        val (sold, pending, available) = client.get<InventoryResponse>(url)
        println("Result: Sold $sold, pending $pending, available $available")
    }
}
Executing in cmd
C:\Users\findu\Development>kotlin petstore.main.kts
# Warnings about reflective access if Java version > 1.8
Result: Sold 4, pending 4, available 666
ToiletPaper 142 Visual

Further Aspects

  • Kotlin scripts are already quite stable, but there are still a few bugs. KT-28475, KT-43520 etc., but they are constantly being fixed.
  • Code: https://jamb.it/kotlinscript
  • I can recommend every Java developer to have a look at Kotlin, it is a nice language.

---

Author: Sebastian Lehrbaum / Software Architect / Business Division Automotive

Wir verwenden Cookies, um unsere Webseite für Sie zu optimieren. Mit dem Besuch unserer Webseite erklären Sie sich damit einverstanden. // Our website is using cookies to improve your experience. By continuing to browse the site, you are agreeing to our use of cookies.

Weitere Informationen finden Sie in unserer Datenschutzerklärung. // For more information, please refer to our privacy policy.

contact icon

Contact us now