Search⌘ K
AI Features

Operator Overloading and Decorator Design Pattern Caveats

Understand how Kotlin’s operator overloading simplifies working with collections and explore the limitations of the Decorator design pattern. Learn practical applications such as using Kotlin’s by keyword and why certain type checks can be challenging with decorators.

Operator overloading

Let’s take another look at the interface that was extracted. Here, we are describing basic operations on a map that are usually associated with an array or map access and assignment. In Kotlin, we have some nice syntactic sugar called operator overloading. If we look at DefaultStarTrekRepository, we can see that working with maps is very intuitive in Kotlin:

starshipCaptains[starshipName] // access
starshipCaptains[starshipName] = captainName // assignment
Retrieving the captain's name of a starship from a map called starshipCaptains

It would be useful if we could work with our repository as if it was a map:

withLoggingAndValidating["USS Enterprise"]
withLoggingAndValidating["USS Voyager"] = "Kathryn Janeway"
Retrieves or adds a captain's name for a starship

Using Kotlin, we can actually achieve this behavior quite easily. First, let’s change our interface:

interface StarTrekRepository {
operator fun get(starshipName: String): String
operator fun set(starshipName: String, captainName: String)
}
Interface for a StarTrekRepository with get and set operators

Note ...