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.
We'll cover the following...
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] // accessstarshipCaptains[starshipName] = captainName // assignment
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"
Using Kotlin, we can actually achieve this behavior quite easily. First, let’s change our interface:
interface StarTrekRepository {operator fun get(starshipName: String): Stringoperator fun set(starshipName: String, captainName: String)}
Note ...