Is it possible to maker a mapping extension functi...
# announcements
p
Is it possible to maker a mapping extension function which will convert the Type of an object. For example, I have a Results sealed class and within it different data classes for different results:
Copy code
sealed class Result<out T : Any?> {
    data class Success<out T : Any>(val data: T) : Result<T>()
    data class Unauthorized(val exception: Exception) : Result<Nothing>()
    data class Timeout(val exception: Exception) : Result<Nothing>()
    data class Error(val exception: Exception) : Result<Nothing>()
}
and I’d like to make a mapping extension function like so Result<EntityModel>.toDomain(DomainModel) which would output Result<DomainModel>. So if the object was Success<UserEntityModel> it would return Success<UserDomainModel>
k
What should the function return if called on
Error
?
k
Sounds like you want a simple mapper
Untitled
j
@Kirill Zhukov but then if I do something like
@GET("/") suspend fun pew(whatever) : Result<PJO>
then in my repositoryImpl for instance how do I say if it's a Result.Success or a Result.Error?
p
@Kirill Zhukov Ah I think I understand the concept, though I’m still confused by generics. In this case since my mapper functions are extension functions would this not work? I can certainly get around this by making specific mappers for each Result<Type> however I was hoping to find a more generic solution. I’m sure it’s a great solution but not sure I fully understand it.
k
My example only applies the mapper to the successful result, you can as well rename the mapper
onSuccess
and add
onFailure
.
What part about generics is confusing?
p
I’m still a relative beginner to programming and honsetly have learnt much about them. I’ll read more about them and then come back to this solution
👍 1