Smartphone

独家优惠奖金 100% 高达 1 BTC + 180 免费旋转




Kotlin and Algebraic Data Types

As Kotlin steadily spreads into the masses more and more Java developers are being exposed to “new” concepts which were actually available in other languages for years now. Algebraic Data Types (ADT for short) is one of these concepts.

Simply spoken, an ADT is a type which is represented by several other subtypes. Still sounds too complicated? Okay. How about this one?

Wait, isn’t this a Java enum? Yes it is. It also happens to be a very simple example of ADT. DeliveryStatus is a type which is indeed represented by several other types (in this case enum entries). But wait, here is more!

Actually, it turns out that when a parcel is dispatched we would also like to know a tracking number.

Here is how an implementation could look like in Java.

Doesn’t look that bad, right? Yet, it is flawed in one important way — trackingNumber is used only if Stage is DISPATCHED and is null in every other case. This is tolerable if the amount of such “special” cases is small, but as code evolves more and more such fields emerge.

Kotlin helps us to solve this problem by providing sealed classes. Here is how you would define an ADT in Kotlin.

Let’s see what’s going here.

Notice that now only DeliveryStatus.Dispatching contains a tracking number. No other types have to know about it.

That is all great but how do we use our DeliveryStatus now? One of the ways would be to use when operator which makes working with ADTs especially convenient.

Important things to notice:

Wait what? You read it right — it indeed does not compile, but can you guess why?

The reason for compilation error also happen to be another advantage of ADTs. It does not compile because we forgot to specify Delivered status in our when clause. Ouch!

Now it works. ADTs are helping you to ensure that when new types are added you handle them properly. But of course you don’t have to do that and if you’ll remove return from showDeliveryStatus it will compile just fine even without Delivered .

Let us know what you think in the comments!

Add a comment

Related posts:

Thoughts for a Rally

I was working in the Emergency Department on election night. People came in in droves with similar complaints — “I don’t know what’s wrong, I have a headache, I’m sick to my stomach, and I can’t stop…

9 Reasons to Apply for an Internship With Assemblyman Randy Voepel

The office of Assemblyman Randy Voepel is proud to offer internship opportunities to anyone wishing to gain valuable experience with the California State Assembly. 3. If you’re still in college, you…