Kotlin Design Patterns — The Command
Just a quick intro to the Command Pattern in Kotlin. And a comparison to it’s Java counterpart.
Kotlin
Java
Output
The code difference between Kotlin & Java is quite significant here. I had to unwrap a few lines just so I could have the code on one page.
Let’s go over the components
OrderCommand: An interface with just an apply/execute method
AddOrderCommand & PayOrderCommand: Two classes implementing the same OrderCommand interface
OrdersCommandProcessor: Manages & executes the commands
Kotlin has apply block, which is an inline function — in simple terms, it recieves this and returns this. Without the apply block, the code would’ve looked very similar to the Java code.
Happy Coding!
Example taken from: Design Patterns in Kotlin
Previous Pattern: The Strategy