Recent Posts
Archives

Posts Tagged ‘SAMconversion’

PostHeaderIcon [KotlinConf2023] Dissecting Kotlin: Exploring Idiomatic Usage of Sealed Types, SAMs, and More with Huyen Tue Dao

Huyen Tue Dao, a respected Android and Kotlin developer (formerly of Trello, more recently Lead Android Developer at Adobe), returned to KotlinConf’23 with her insightful talk, “Dissecting Kotlin: Unsealing the Sealed, the SAM, and Other Syntax”. Continuing her exploration of what constitutes “idiomatic Kotlin,” Huyen examined several language and library features introduced or refined over the past few years, delving into their semantics, syntax, and underlying implementations to understand their best use cases and how they fit into Kotlin’s broader themes. She referenced Andre Breslav’s 2018 KotlinConf keynote, which emphasized Kotlin’s pragmatic goals: readability over concision, reuse over expressiveness, interoperability, and safety/tooling.

Huyen’s approach involved dissecting features to see if they guide developers toward more idiomatic Kotlin or present choices where idiomatic usage might be nuanced.

Sealed Hierarchies: Evolution and Flexibility

Huyen began by revisiting sealed classes and interfaces, a cornerstone for modeling restricted hierarchies, often used for representing states or a fixed set of types. Key evolutions she discussed include:
* Sealed Interfaces (Kotlin 1.5): Previously, sealed hierarchies were restricted to sealed class and abstract class. The introduction of sealed interface provided more flexibility, allowing classes to implement multiple sealed interfaces and enabling a wider range of domain modeling possibilities. She illustrated this by evolving a movie genre example, initially a sealed class, to use sealed interfaces for sub-genres, demonstrating how a class (e.g., a specific movie) could belong to multiple genre classifications.
* Unsealing Sealed Classes (Implicitly): While not “unsealing” in the sense of breaking the restriction, the ability for subclasses of sealed classes to be defined in different files within the same compilation unit and module (introduced before Kotlin 1.5 for sealed classes, and a natural fit for sealed interfaces) offers more organizational flexibility for larger hierarchies.
* Data Objects (Kotlin 1.9): For singleton instances within a sealed hierarchy (or elsewhere) that benefit from data class-like behavior (e.g., a meaningful toString()), Kotlin 1.9 introduced data object. This combines the singleton nature of object with the auto-generated toString, equals, and hashCode methods of data classes, providing a cleaner way to represent simple, named instances in a hierarchy.

A “bytecode break” showed that sealed classes are compiled as abstract classes with private constructors and that their permitted subclasses are often checked using instanceof and specific class metadata generated by the compiler.

Unsigned Integers and Value Classes: Expressiveness and Performance

Huyen then explored features aimed at enhancing expressiveness and performance around data representation:
* Unsigned Integer Types (UByte, UShort, UInt, ULong – Stable in Kotlin 1.5): These types provide a way to represent non-negative numbers, utilizing the full bit-width for the magnitude. This is particularly useful when interacting with native APIs (like C++) that use unsigned types, or when dealing with data where negative values are meaningless (e.g., quantities, bitmasks). They come with their own set of operations and ranges. Huyen highlighted how they avoid the complexities of two’s complement interpretation when only positive values are needed.
* Value Classes (Inline Classes became Value Classes, stable with JVM backend in Kotlin 1.5): Value classes (@JvmInline value class) are wrappers around a single underlying property. Their primary benefit is providing type safety for primitive-like data (e.g., Email, UserId, Frequency) without the runtime overhead of heap allocation for the wrapper object in many cases. When possible, the compiler “inlines” the value, using the underlying type directly in bytecode, thus avoiding object allocation and offering performance benefits similar to primitives while retaining type distinction at compile time. Huyen used an audio processing example with distinct types like Frequency, SamplingRate, and FramesPerBuffer to illustrate how value classes can prevent accidental misuse of simple types like Int or Float.

SAM Conversions and Functional Interfaces: Java Interop and Kotlin Idiom

Finally, Huyen discussed Single Abstract Method (SAM) interfaces and Kotlin’s fun interface:
* SAM Conversions for Java Interfaces: Kotlin has long supported SAM conversions for Java interfaces, allowing a lambda to be used where an instance of a Java interface with a single abstract method is expected.
* fun interface (Kotlin 1.4): To enable similar idiomatic usage for Kotlin-defined interfaces, Kotlin introduced fun interface. By marking a Kotlin interface with the fun keyword, developers explicitly opt-in to SAM conversion, allowing a lambda to be directly passed where an instance of that interface is required. This promotes a more functional style and reduces boilerplate for simple callback-like interfaces. This feature aims to provide compatible syntax between Java and Kotlin code for functional interfaces.

Huyen concluded by reiterating that while understanding syntax and semantics is helpful, “idiomatic Kotlin” ultimately is about what best solves the problem at hand for the developer and their team, aligning with Kotlin’s pragmatic principles.

Links: