Skip to Content
Course content

178: Kotlin Notebook Basics

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

I've spent far too many hours of my career creating "TemporaryProject1", "Temp2", and "TestProject_Final" just to check if a specific library function works the way I think it does. It's a slog. You have to set up the Gradle build, wait for the index, write a main function, and run the whole JVM just to test five lines of code. This is exactly why I started using Kotlin Notebooks.

Getting out of the "Main" function rut

Let's say I'm trying to build a small utility that calculates a "Readability Score" for a piece of text based on sentence length. In a standard project, I'd be writing a class and a wrapper. Here, I'm just going to open a .ipynb file in IntelliJ and toss this in a cell:

fun calculateScore(text: String): Double {
    val sentences = text.split(Regex("[.!?]")).filter { it.isNotBlank() }
    val words = text.split(Regex("\\s+")).filter { it.isNotBlank() }
    return words.size.toDouble() / sentences.size
}

I hit Shift+Enter. Nothing happened? Well, actually, it did. The cell executed, the function is now defined in the notebook's memory, and I didn't have to write fun main(). I can just create a second cell and call it immediately:

val sampleText = "Kotlin is great. I love notebooks! Do you?"
calculateScore(sampleText)

The output prints right below the cell. It's an interactive REPL on steroids. The most important thing to realize here is that the notebook maintains state. The calculateScore function lives on in the background until I restart the kernel.

The "Where is my library?" moment

Now, I want to do something a bit more complex. I want to use the kotlinx-datetime library to timestamp when these scores are calculated. I'll try to use Clock.System.now() in a new cell:

val now = Clock.System.now()
println("Calculated at $now")

And... it fails. Red squiggles everywhere. The notebook doesn't magically know every library in existence; it only knows the Kotlin standard library by default. In a regular project, I'd go to build.gradle.kts, add the implementation line, and sync. But that ruins the "quick experiment" vibe. Instead, I'll use the @file:DependsOn annotation at the very top of my notebook:

@file:DependsOn("org.jetbrains.kotlinx:kotlinx-datetime:0.4.0")

import kotlinx.datetime.*

I run that cell, and suddenly the IDE recognizes the types. I love this because I can keep my dependencies documented right inside the notebook without leaving the editor.

Tuning the logic on the fly

Here is where the real power kicks in. I realize my calculateScore is too simple—it's not handling empty strings well. In a traditional IDE workflow, I'd change the function, re-compile, and re-run the whole app. Here, I just go back to the first cell, tweak the code, and run just that cell again:

fun calculateScore(text: String): Double {
    if (text.isBlank()) return 0.0
    val sentences = text.split(Regex("[.!?]")).filter { it.isNotBlank() }
    if (sentences.isEmpty()) return 0.0
    val words = text.split(Regex("\\s+")).filter { it.isNotBlank() }
    return words.size.toDouble() / sentences.size
}

Now, when I go back to my test cell and run it again, it uses the updated logic. I'm essentially iterating on a live object. It feels less like "software engineering" and more like "sketching," which is exactly what you want when you're in the exploration phase of a feature.




📋 Practical Task

Build a Weather Data Transformation Sandbox

Your goal is to use a Kotlin Notebook to prototype a data cleaner. Instead of a full project, create a notebook that does the following:

  • Use @file:DependsOn to include the org.jetbrains.kotlinx:kotlinx-datetime:0.4.0 library.
  • In one cell, define a data class WeatherReading(val temp: Double, val city: String, val timestamp: Instant).
  • In a second cell, create a list of WeatherReading objects with some dummy data (include at least one reading with a temperature that seems like an error, e.g., 500.0 degrees).
  • In a third cell, write and test a function filterAnomalies(readings: List<WeatherReading>) that removes any readings where the temperature is outside the range of -100.0 to 60.0.
  • Verify that your filter works by printing the size of the list before and after the function call in a final cell.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.