Kotlin
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Null Safety
-
Section 4: Object-Oriented Kotlin
-
Section 5: Functional Kotlin
-
Section 6: Coroutines
-
Section 7: Collections Deep Dive
-
Section 8: Type System Deep Dive
-
Section 9: Interop and Tooling
-
Section 10: Kotlin DSLs and Patterns
-
Section 11: Testing and Quality
-
Section 12: Server-Side Kotlin
-
Section 13: Practical Projects
-
Section 14: Interview Practice
-
Section 15: More Practice Exercises
-
Section 16: More Standard Library
-
Section 17: Multiplatform Kotlin
-
Section 18: kotlin.collections In Depth
-
Section 19: kotlin.text In Depth
-
Section 20: kotlin.ranges and kotlin.sequences
-
Section 21: kotlin.io and File Handling
-
Section 22: kotlinx.coroutines Deep Dive
-
Section 23: kotlin.reflect
-
Section 24: Android Development with Kotlin Overview
-
Section 25: Kotlin Multiplatform Deep Dive
-
Section 26: Kotlin for Backend Deep Dive
-
Section 27: Kotlin Design Patterns
-
Section 28: Advanced Language Features
-
Section 29: More Practice Exercises
-
Section 30: More Interview Practice
-
Section 31: Kotlin Type System Deep Dive
-
Section 32: Kotlin Null Safety Advanced
-
Section 33: Kotlin Testing Deep Dive
-
Section 34: Kotlin Build Tooling Deep Dive
-
Section 35: Kotlin Serialization
-
Section 36: Kotlin Performance Considerations
-
Section 37: Kotlin Native Overview
-
Section 38: Kotlin for Data and Scripting
-
Section 39: More Coroutines Practice
-
Section 40: More Android-Adjacent Patterns
-
Section 41: More Practical Projects
-
Section 42: More Design and Architecture Practice
-
Section 43: Kotlin Language Evolution
-
Section 44: More Interview and Review
-
Section 45: Kotlin Delegation Patterns Deep Dive
-
Section 46: Kotlin Annotations Deep Dive
-
Section 47: Kotlin for Gradle Plugin Development
-
Section 48: Kotlin Concurrency Beyond Coroutines
-
Section 49: Kotlin Compiler Internals
-
Section 50: Real-World Kotlin Case Studies
-
Section 51: Final Practice Projects
-
Section 52: Kotlin for Server-Side Reactive Programming
-
Section 53: More Practice and Drills
-
Section 54: Kotlin Security Practices
128: The Adapter Pattern in Kotlin
Why can't I just change the library code to fit my interface?
That's the first question everyone asks. In a perfect world, you'd just go into the source code and rename the methods to match your project's standards. But in the real world, you're usually dealing with a third-party SDK, a legacy JAR file from five years ago, or a teammate's module that you're too afraid to touch because it's the only thing keeping the production server alive.
The Adapter pattern is your way of saying, "I can't change how this external tool works, but I can build a wrapper around it that makes it look and feel like the rest of my system." It's like using a physical travel adapter when you go to Europe; you aren't rewiring your laptop's power supply, you're just creating a bridge between two incompatible plugs.
How do I actually implement this in Kotlin?
Let's say you're building a music app. Your app expects every audio source to follow a simple AudioPlayer interface. But then you decide to integrate a fancy new AdvancedStreamingService from a vendor. The problem? Their method names are completely different.
interface AudioPlayer {
fun play(trackId: String)
fun stop()
}
// This is the "Adaptee" - the class we can't change
class AdvancedStreamingService {
fun streamAudio(id: String, quality: String = "High") {
println("Streaming $id in $quality quality...")
}
fun terminateConnection() {
println("Connection closed.")
}
}
To make this work, you create an Adapter class that implements your interface but delegates the actual work to the vendor's service. I usually name these classes [Vendor]Adapter to keep things clear.
class StreamingServiceAdapter(
private val vendorService: AdvancedStreamingService
) : AudioPlayer {
override fun play(trackId: String) {
// We map our 'play' call to their 'streamAudio' call
vendorService.streamAudio(trackId)
}
override fun stop() {
// We map our 'stop' call to their 'terminateConnection'
vendorService.terminateConnection()
}
}
Now, the rest of your app doesn't even know the AdvancedStreamingService exists. It just sees an AudioPlayer and calls play(). If you decide to switch vendors next month, you only have to write one new adapter instead of hunting through your entire codebase for every instance of streamAudio().
Is there a more "Kotlin-esque" way to do this without so much boilerplate?
If your adapter needs to expose some of the original methods of the adaptee while still conforming to an interface, you can use Kotlin's class delegation (the by keyword). This prevents you from having to manually write "pass-through" methods for every single function in the external class.
Imagine the vendor service has twenty different configuration methods. You don't want to override all twenty in your adapter. Instead, you can do this:
class SmartAdapter(private val service: AdvancedStreamingService) : AudioPlayer, AdvancedStreamingService by service {
override fun play(trackId: String) {
service.streamAudio(trackId)
}
override fun stop() {
service.terminateConnection()
}
}
By using by service, the SmartAdapter automatically inherits all the methods of AdvancedStreamingService, but you still get to override the specific ones needed to satisfy the AudioPlayer interface. It's a clean way to keep the "bridge" open without writing a mountain of repetitive code. Just be careful: you're exposing the vendor's API to your business logic, which slightly weakens the encapsulation. Use it when the convenience outweighs the risk.
📋 Practical Task
Exercise: Adapting a Legacy XML Weather Provider
You are working on a modern weather dashboard that expects a WeatherProvider interface. However, the company just bought a legacy system that provides weather data in a clunky XML-style string format. Your task is to create an adapter that translates the legacy XML output into a modern Kotlin data class.
Given:
data class WeatherReport(val temp: Double, val condition: String)
interface WeatherProvider {
fun getCurrentWeather(city: String): WeatherReport
}
class LegacyWeatherSystem {
// Returns a string like: "<temp>22.5</temp><cond>Sunny</cond>"
fun fetchXmlWeather(city: String): String {
return "<temp>22.5</temp><cond>Sunny</cond>"
}
}
Your Task:
- Create a class named
LegacyWeatherAdapterthat implementsWeatherProvider. - The adapter should take an instance of
LegacyWeatherSystemin its constructor. - Inside
getCurrentWeather, callfetchXmlWeatherand parse the string to return aWeatherReportobject. (For the sake of this exercise, you can use simple string manipulation likesubstringAfterandsubstringBeforeto extract the values). - Verify your adapter by initializing it with the legacy system and printing the temperature of a city to the console.
There are no comments for now.