Kotlin Functions

 

Discover the Automation Potential with Kotlin: Scripting Made Simple

Kotlin has earned popularity as a concise and expressive language, primarily for Android development. However, its capabilities stretch beyond just mobile development. Kotlin can be an excellent tool for scripting, allowing developers to automate tasks with ease. Kotlin scripts use the `.kts` file extension and can run just like any other script on your computer.

Discover the Automation Potential with Kotlin: Scripting Made Simple

In this blog post, we will delve deep into Kotlin scripting and demonstrate how to automate some everyday tasks using Kotlin.

1. Advantages of Kotlin Scripting

  1. Concise Syntax: Kotlin’s brevity reduces boilerplate, making scripts easy to write and maintain.
  1. Interoperability with Java: Kotlin scripts can leverage the vast Java ecosystem.
  1. Type Safety: Kotlin provides compile-time error checks, which makes scripting safer.

1.1. Setting Up:

Before scripting, ensure you have the Kotlin compiler installed. You can get it through the Kotlin website or using SDKMAN:

```bash
sdk install kotlin
```

Now, create a `.kts` file for your script:

```bash
touch my_script.kts
```

2. File Management

Imagine you have a directory with thousands of files, and you wish to archive (zip) all files created in the last 7 days.

```kotlin
import java.io.File
import java.util.zip.ZipEntry
import java.util.zip.ZipOutputStream

fun archiveRecentFiles(directory: String, days: Int, outputZip: String) {
    val targetDir = File(directory)
    val now = System.currentTimeMillis()

    ZipOutputStream(File(outputZip).outputStream()).use { zos ->
        targetDir.listFiles { file ->
            (now - file.lastModified()) <= days * 24 * 60 * 60 * 1000
        }?.forEach { file ->
            zos.putNextEntry(ZipEntry(file.name))
            file.inputStream().use(zos::writeBytes)
            zos.closeEntry()
        }
    }
}

archiveRecentFiles("./my_directory", 7, "recent_files.zip")
```

3. Processing JSON Data

Suppose you have a JSON file `data.json`:

```json
[
    {"id": 1, "name": "Alice", "email": "alice@example.com"},
    {"id": 2, "name": "Bob", "email": "bob@example.com"}
]
```

You wish to extract all emails:

```kotlin
import kotlinx.serialization.*
import kotlinx.serialization.json.*

@Serializable
data class User(val id: Int, val name: String, val email: String)

fun extractEmails(filePath: String): List<String> {
    val content = File(filePath).readText()
    val users = Json.decodeFromString<List<User>>(content)
    return users.map { it.email }
}

println(extractEmails("./data.json"))
```

4. Web Scraper

A simple web scraper to fetch and print the titles of the latest blog posts from a hypothetical blog:

```kotlin
import org.jsoup.Jsoup

fun fetchLatestBlogTitles(url: String, cssQuery: String): List<String> {
    val doc = Jsoup.connect(url).get()
    return doc.select(cssQuery).map { it.text() }
}

val titles = fetchLatestBlogTitles("https://example-blog.com", ".post-title")
titles.forEach(::println)
```

5. Cron-like Task Scheduler

A script to run another script or command periodically:

```kotlin
fun executePeriodically(command: String, intervalMillis: Long) {
    while (true) {
        ProcessBuilder(command.split(" ")).start().waitFor()
        Thread.sleep(intervalMillis)
    }
}

executePeriodically("./backup_database.kts", 24 * 60 * 60 * 1000) // Executes daily
```

6. Tips for Kotlin Scripting

  1. Shebang for Direct Execution: By adding `#!/usr/bin/env kotlinc -script` to the top of your `.kts` file, you can run it directly from a Unix-like terminal using `./script_name.kts`.
  1. Use External Libraries: Kotlin scripts can pull in dependencies with the `@file:DependsOn` or `@file:Repository` annotations. For instance, the Jsoup library in our web scraper example would be imported at the top of our script with `@file:DependsOn(“org.jsoup:jsoup:1.13.1”)`.
  1. Leverage Scripting API: Kotlin provides a `Scripting API` which offers deeper configuration of the scripting environment, like defining implicit receivers or importing commonly used libraries by default.

Conclusion

Kotlin scripting offers a powerful and concise way to automate tasks. From file management, data processing, web scraping, to task scheduling, the possibilities are vast. The ability to tap into the rich Java ecosystem while enjoying Kotlin’s concise syntax gives Kotlin scripting an edge. Give it a try the next time you need to automate a task!

Previously at
Flag Argentina
Brazil
time icon
GMT-3
Experienced Android Engineer specializing in Kotlin with over 5 years of hands-on expertise. Proven record of delivering impactful solutions and driving app innovation.