Skip to Content
Course content

176: Kotlin Scripting (.kts files)

Click on the "Edit" button in the top corner of the screen to edit your slide content.

I've spent a lot of time recently writing utility scripts for my CI pipeline. Usually, I'm tempted to just write a full Kotlin project, but the overhead—creating a src/main/kotlin folder, setting up a build.gradle.kts, and defining a main function—feels like overkill when I just need to parse a few files and move them around.

Trying to run code without the boilerplate

I started by trying to do something simple: read a log file and count how many "ERROR" entries exist. If I were doing this in a standard .kt file, it would look like this:

fun main() {
    val lines = java.io.File("app.log").readLines()
    val errors = lines.count { it.contains("ERROR") }
    println("Found $errors errors.")
}

It works, but honestly? I hate writing fun main() { ... } every time I just want to test a quick logic snippet. I wondered if I could just strip the function wrapper and run the code directly. I tried saving the contents of that main block into a file called analyze.kt and running it. predictably, the compiler complained. It told me it couldn't find the entry point. Kotlin, by default, is a compiled language; it needs a very specific starting line to know where the execution begins.

The magic of the .kts extension

Then I remembered the .kts extension. The "s" stands for scripting. I renamed my file to analyze.kts and removed the main function entirely. Now the file looks like this:

val lines = java.io.File("app.log").readLines()
val errors = lines.count { it.contains("ERROR") }
println("Found $errors errors.")

When I ran this using the Kotlin runner, it actually worked. No main, no class wrappers, nothing. I realized what's happening under the hood: the Kotlin script engine is essentially wrapping my code in an implicit main function for me. It treats the entire file as the body of a function. This is a huge time-saver for "glue code"—those little scripts that connect two bigger systems.

Experimenting with imports and types

I wanted to make the script a bit more robust, so I tried adding a helper function inside the script to filter out different log levels. I wondered: Can I actually define functions in a script, or is it just one long list of commands?

import java.io.File

fun countOccurrences(file: File, keyword: String): Int {
    return file.readLines().count { it.contains(keyword) }
}

val logFile = File("app.log")
println("Errors: ${countOccurrences(logFile, "ERROR")}")
println("Warnings: ${countOccurrences(logFile, "WARN")}")

This worked perfectly. The script engine handles the top-level declarations just fine. However, I noticed something odd. When I tried to use some complex generics or certain annotations that I normally use in my main project, the IDE's autocomplete felt a bit sluggish compared to a standard .kt file. That's because the IDE has to do a bit more guesswork to figure out the context of a script since there isn't a formal project structure surrounding it. It's a small price to pay for the agility, though.

When to actually use this

After playing around with this, I've realized that .kts isn't meant to replace your application code. You wouldn't write your entire backend in a script file; you'd lose out on build optimizations and structure. But for things like Gradle build scripts (which are .gradle.kts), automation tasks, or even simple data migration scripts, it's a superpower. You get the full type safety of Kotlin without the ceremony of a JVM project.




📋 Practical Task

Build a Directory Space Auditor Script

Create a Kotlin script file (auditor.kts) that performs the following task:

  • Accepts a directory path as a variable (you can hardcode a path to a folder on your machine for this exercise).
  • Iterates through all files in that directory.
  • Calculates the total size of all files in bytes.
  • Prints a report listing each file name and its size, followed by the final total sum.

Requirements:
Use java.io.File to handle the directory and file operations. Ensure you do not wrap your code in a main function; write it as a pure script.

Rating
0 0

There are no comments for now.

to be the first to leave a comment.