This article will take about 3 minutes to read.
If you follow the Jetbrains blog you may have heard that there is a new plugin called Kotlin Notebook for running Notebooks using kotlin. I’ve been trying it out over the last few weeks, and I’ve been loving it.
If you haven’t heard of notebooks are - they let you define a series of “cells” which can run code. It’s a wonderful combination of traditional development, with production grade tooling, but with the flexibility and prototyping of Excel.
That last bit is key. I deal with financial statements a lot, and kotlin notebook now allows me to group transactions into virtual accounts, so I can see who has paid how much, and when, at a glance. Since I’m using kotlin, if an account is mislabelled, all I need to do is String.replace(x,y)
.
These are some of my takeaways.
You can limit the scope for a set of variables by wrapping them in run {}
.
// this is the content of a single cell
run {
val x = 0
val y = 1
println(x + y)
}
run {
val x = 2
val y = 3
println(x * y)
}
You can see that I’ve used the same variable names twice here, and they’re properly scoped. This will do pretty much as you expect, printing out 1
, then 6
.
If this were split into 2 cells, and run one after the other, it would continue to work as expected - whereas, if you did not include the run blocks, you’d be reassigning the original val
.
Unit
When you run a cell, it will print out the result of the last evaluation. That means that if your cell looks like this
1 + 1
it will automatically print 2
after the cell is run, just like it would in python or javascript.
You can get around this by ending the cell with Unit
1 + 1
Unit
which will not render any output.
All you need to do is create a markdown cell (using right-click > “Convert cell to Markdown”), and enter in some LaTeX code like this
$$
y = m \cdot x + b
$$
Keeping this close to the code can be a great way to verify the accuracy of your program later on.
There is a lot of hype about kotlin DataFrames, and they are a cool piece of technology, but they can be overkill for some tasks.
The code that you write in a Notebook is fairly transient, because you will generally have a specific data-oriented goal in mind, and once you complete that task you’re unlikely to run the notebook again. If you do - it might be time to convert the notebook to an actual project.
Notebooks are there to help you move fast, and finish those data goals quickly - so if you start by loading information into a DataFrame
, and you find that the syntax is slowing you down, you can always .map{}
the data into a data class and continue in pure kotlin.
There is a lot to love about Notebooks - especially now that they are available in kotlin. Keep tabs on the Kotlin for Data Science page for more updates on this new tech, and check out their list of libraries which work well with Notebooks.