Easily Manage Image Type With Sealed Classes

Abhishek Saxena
Level Up Coding
Published in
2 min readNov 29, 2021

--

Photo by Pablo Arroyo on Unsplash

With the introduction of sealed classes in Kotlin, it opened up a way to easily handle restricted hierarchies.

The most common use case of a sealed class is with the handling Result<T> of an API response.

…..but there are way more applications of the sealed classes than you can imagine. I’ll discuss one of them here, which would be to handle image type in android.

The source of the image can either be remote, i.e, a URL or local storage. Since the resource can come from only these two types, it makes a perfect use case for the sealed classes.

You can use the Image everywhere in the project and easily refer to either of the two.

Example:

Additionally, you can easily load images with the image loading library like Glide

You can use it with Jetpack Compose.

You can create a composable that consumes a UiImage, that in-app code ends up being remote, but for previews, you can supply a drawable res, so I can see the full behavior

Example

Conclusion

Kotlin sealed classes are really powerful when you have a strict hierarchy of classes. Herewith the images, you can even extend the usage to text as it can be directly passed as a string or as a reference of the string resource.

A special thanks to Adam McNeilly for the feedback and suggestions.

Thank you very much for reading the article. I hope you liked it. Do you have any feedback? Comment below or reach out to me on Twitter.

— — Abhishek Saxena

--

--

I am a Mobile Full Stack Developer with 2 years of experience with expertise in Native Android and Spring Boot. https://github.com/5AbhishekSaxena