Skip to content

Adapter (Structural Patterns) - using extension function #1

@MrGrees

Description

@MrGrees

I see the tendency that a lot of programmers write code that is more function-based.

Therefore, I propose adding another option to the Adapter Pattern using the Kotlin extension function.

Using WeatherData-WeatherPresentation example:

data class WeatherData(/* ... */)

data class WeatherPresentation(/* ... */)

fun WeatherData.toWeatherPresentation() = WeatherPresentation(
    tempDisplay = "${this.temperature}°C",
    humidityDisplay = "${this.humidity}%",
    windDisplay = "${this.windSpeed} m/s",
    weatherIcon = when (this.condition.lowercase()) {
        "sunny" -> R.drawable.ic_launcher_foreground
        "cloudy" -> R.drawable.ic_launcher_background
        "rainy" -> R.drawable.ic_launcher_foreground
        else -> R.drawable.ic_launcher_background
    }
)

@Composable
fun WeatherScreen(weatherData: WeatherData) {
    val presentation = weatherData.toWeatherPresentation()

    Column(modifier = Modifier.padding(16.dp)) {
        Text("Temperature: ${presentation.tempDisplay}")
        Text("Humidity: ${presentation.humidityDisplay}")
        Text("Wind Speed: ${presentation.windDisplay}")
        Image(
            painter = painterResource(presentation.weatherIcon),
            contentDescription = "Weather Icon",
            modifier = Modifier.size(50.dp)
        )
    }
}

Additionally, using extension functions may be more intuitive (e.g., in lists):

fun Foo(weathersData: List<WeatherData>) {
    val weathersPresentation = weathersData.map { it.toWeatherPresentation() }
    // ...
}

instead of

fun Foo(weathersData: List<WeatherData>) {
    val adapter = WeatherDataAdapter()
    val weathersPresentation = weathersData.map { adapter.adapt(it) }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions