Say I have the following four classes: ```* Databa...
# announcements
j
Say I have the following four classes:
Copy code
* DatabaseKennelModel
    + dogs: List<DatabaseDogModel>

* DatabaseDogModel
    + name: String

* Kennel
    + dogs: List<Dog>

* Dog
    + name: String
Is there a better way to transform a
List<DatabaseKennelModel>
into a
List<Kennel>
, than the following:
Copy code
databaseKennelModelList.map { databaseKennelModel ->
    Kennel(
        dogs = databaseKennelModel.dogs.map { databaseDogModel ->
            Dog(
                name = databaseDogModel.name
            )
        }
    )
}
☝️ it works, but I'm wondering is there anything I can do to avoid that nested
map
?
t
You’re trying to transform a list of
DatabaseKennels
into
Kennels
and a list of
DatabaseDogs
into
Dogs
, so you can’t really avoid two transformation functions (two maps)
In any case, what you’re doing looks perfectly reasonable. What is it about the nested map that you don’t like?
j
oh there was nothing in particular, I was just wondering if there was a better way I guess ¯\_(ツ)_/¯
d
You could remove the explicit nesting by separating it out into functions/extension functions
Copy code
fun List<DatabaseKennelModel>.toKennelList() = this.map { Kennel(dogs = it.dogs.ToDogList()) }

fun List<DatabaseDogModel>.toDogList() = this.map { Dog(name = it.name) }
but that just changes the way it looks. You could as easily also make a similar but for operating on Kennel or Dog directly
Copy code
fun DatabaseKennelModel.toKennel() = Kennel(dogs = this.dogs.map { it.toDog() })

fun DatabaseDogModel.toDog() = Dog(name = this.name)
and then call it as
Copy code
databaseKennelModelList.map { it.toKennel() }
It depends if your concern is around performance, how it looks, maintainability, or some other concern? But I agree with above, nothing looks wrong with your current approach