Skip to Content
Course content

128: The Adapter Pattern in Kotlin

Click on the "Edit" button in the top corner of the screen to edit your slide content.

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 LegacyWeatherAdapter that implements WeatherProvider.
  • The adapter should take an instance of LegacyWeatherSystem in its constructor.
  • Inside getCurrentWeather, call fetchXmlWeather and parse the string to return a WeatherReport object. (For the sake of this exercise, you can use simple string manipulation like substringAfter and substringBefore to extract the values).
  • Verify your adapter by initializing it with the legacy system and printing the temperature of a city to the console.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.