Skip to content

Instantly share code, notes, and snippets.

@oscargrgm
Last active June 30, 2021 11:06
Show Gist options
  • Save oscargrgm/94a30289680f4986d12809b830843d97 to your computer and use it in GitHub Desktop.
Save oscargrgm/94a30289680f4986d12809b830843d97 to your computer and use it in GitHub Desktop.
Mapper to convert network data into domain model and viceversa.
interface Mapper<D, M> {
fun toModel(data: D): M
fun toData(model: M): D
}
object ModelMapper : Mapper<Data, Model> {
override fun toModel(data: Data): Model = with(data) {
Model(...)
}
override fun toData(model: Model): Data = with(model) {
Data(...)
}
}
fun <D, M> Result<D>.toResultModel(mapper: Mapper<D, M>): Result<M> = when (this) {
is Result.Success<D> -> Result.Success(mapper.toModel(this.value))
is Result.Error<D> -> Result.Error(this.exception)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment