5 Pro Kotlin Dev Hacks For More Assertive Code

Serious pro Kotlin techniques for serious pro Kotlin devs

Sam Cooper
6 min readJun 12, 2023
Photo by Bill Jelen on Unsplash

As a serious pro Kotlin dev, do you feel like the Kotlin compiler is holding you back?

Kotlin is full of type safety features and clever compile-time checks. These can be great guardrails for newcomers and junior engineers. But for an experienced pro Kotlin dev, is all that hand-holding null-safety really needed? Why does the compiler always seem to think it knows better than you?

Luckily, Kotlin’s type-safety systems have some hidden advanced-level features that you can use to override and customise their syntax and behaviour to better suit your needs.

Here are five serious pro Kotlin dev techniques you can use to reassert your dominance over the Kotlin compiler and make your code more expressive, more assertive, and just generally more pro.

All the examples in this article are real Kotlin code that you can run and even edit as you go.

1. Assert it like you mean it

The double bang (!!) operator in Kotlin asserts that a value is non-null. This is often needed in situations where you’re right and the compiler is wrong.

Less-experienced Kotlin programmers will often commit the error of including a double bang after a variable to indicate that they’re pretty sure it won’t ever be null. They might even include a comment to explain why it’s safe.

But this is actually a big mistake. As an experienced Kotlin programmer, you can be confident that you know what you’re doing. And skilled engineers don’t need comments, because they know how to write clean code that’s clear and self-explanatory.

Make sure that everyone who reads your code knows that this variable is definitely, absolutely not null by including several exclamation points for good measure. The exact number will vary depending on the situation, but I normally go for at least twelve.

2. Question everything

Now that you know how to use multiple exclamation points to convey intent, you don’t need to worry about null-checks or non-null types any more. Those are helpful guardrails for newcomers, but pro Kotlin devs are skilled enough to keep track of null references themselves.

That’s great when you’re calling your own code, but what if you need to integrate with any API that was written by someone else? Code written by a non-expert is probably riddled with misplaced null values, and as a diligent engineer you need to protect yourself and others from the risk that poses.

This is where the “nullability equivocation” pattern comes in. When you’re working on shared code and need to pass a value that might be null, include additional question marks after the type to indicate your level of confidence. One or two question marks means it’s probably safe to use. More than ten question marks indicates significant uncertainty, and ensures that when the code crashes, everybody will know it’s not your fault.

Nullability equivocation pairs really well with non-null assertions. Treat the number of question marks in a type definition as a direct suggestion for how many exclamation points to use — more question marks generally means fewer exclamation points are warranted at the use site.

3. Throw it like it’s hot

Throwing exceptions is a great way to quickly get a value from one place to another, especially in more advanced pro functions that are doing several different things at once. Exceptions don’t need to be declared in the function signature, so you can ignore the type system and just get the value directly where it needs to go.

As you gain experience in Kotlin, you’ll find that you use more and more exceptions, and fewer and fewer actual function return types. These days, most of my functions just return Unit, and their return values are ejected by catching an exception several levels up the call stack in a complex structure that more junior engineers just wouldn’t be expected to comprehend.

Because we can use exceptions for so many things in Kotlin, we need a good way to distinguish real errors from ordinary control-flow exceptions. Luckily, the language has our backs once again.

When you need to draw extra attention to an exception, just repeat the throw keyword a few times. For non-fatal exceptions, or things that you know you’re going to catch right away, use a normal single throw. This conveys intent and lets people know that it’s not really a big deal. For more serious errors, consider using as many as ten or twelve throw keywords in front of it. For added impact, split the whole thing onto multiple lines to create some visual separation that really makes the code stand out.

Bonus tip: to really level up your exception-throwing game, take advantage of the double-bang operator to underline the severity of the error. A double exclamation point can be added after any value in Kotlin, and throwing an exception is a perfect place to leverage its expressivity.

If you want to learn more about creative ways to use the throw keyword in Kotlin, take a look at my article about “Short Circuits, Bottom Types, and the Vacuous Boomerang.”

4. Unary ingenuity

If you’re at an advanced level as a pro Kotlin dev, you should definitely be using the “unary plus” operator. When applied to numeric values, this is one of the most useful operators in the language, because it lets you return the input value unmodified, without doing anything to it at all.

Just like the question mark and double bang operators, the unary plus operator can be repeated as many times as you like without affecting the result. The possibilities really are endless with this one. Because it doesn’t do anything at all, it can be used wherever you like.

I like to use the unary plus operator to space out complex mathematical expressions, making them easier for my more junior colleagues to read.

When used to prefix a numeric literal, it can also be a great way to indicate your level of confidence that the value is correct, or just to provide some extra indentation when you want to vertically align several variable declarations.

What advanced uses can you think of for the unary plus operator?

5. How long is an empty string?

One of the ways pro Kotlin devs make code clean and readable is to avoid using “magic” numbers and strings. Literal values appearing in code should always be assigned to a named variable before being used.

If you’re an expert Kotlin engineer working as a tech lead for a large team, you’ve hopefully set up all your projects with some basic helpful named constants that you know everybody will need. At a minimum, you should have const val EMPTY_STRING = "" and const val ZERO = 0.

Unfortunately, this can often create confusion for more junior engineers. Their lack of experience means they don’t always understand the benefits that good named constants can provide for pro enterprise Kotlin software delivery, and so they might ask questions like, “why do we need a named constant if the name is longer than the actual value?”

It’s easy to head off these difficult conversations for the numeric constants. Just use the unary plus operator to make the value a bit longer, so that it looks like it’s doing something important.

But the unary plus operator isn’t available in the standard library for strings. I’m assuming that’s just an oversight, as I don’t think it’s too hard to implement. Luckily, there’s an advanced-level string interpolation technique that’s also perfect for this scenario.

By combining string templates, you can create pretty much any length of empty string you like. It’s up to you whether you want to nest the strings inside one another or just place a few of them side-by-side — the compiler is great at optimising these expressions so that the resulting empty string is created as efficiently as possible.

Bonus round: putting it all together

Hopefully these super advanced pro Kotlin tips have helped you level up your skills and write more expressive code. To wrap it all up, here’s an example of an expert-level program that combines all the techniques we’ve learned.

--

--