andrzej
09/16/2019, 10:45 AMUser(firstName: String, lastName: String, age: Int)
to UserEntity(name: String, age: Int)
. I found that using a scope function is very useful but I don't know which would be the best. The pros and cons are as follows:
• let
seems as natural choice since it returns lambda result but having to repeat it
for every property feels a little redundant, e.g. user.let { UserEntity(it.firstName + it.lastName, it.age)}
• run
allows to eliminate it
from the above example but run
looks awkward as a mapping function, e.g. user.run { UserEntity(firstName + lastName, age)}
• with
also seems a viable option, e.g. with(user) { UserEntity(firstName + lastName, age)}
but I'm not sure if this is intended usage of with
function, in Kotlin docs it is described as a function which lambda result should not be returned or as way to introduce a helper object (https://kotlinlang.org/docs/reference/scope-functions.html), so I'm not surewasyl
09/16/2019, 10:48 AMfun User.toEntity() = UserEntity(firstName + lastName, age)
and then write let(User::toEntity)
. This way I feel I get the best of two worldsstreetsofboston
09/16/2019, 11:26 AMandrzej
09/16/2019, 12:09 PMrun
in my case: Use ‘run’ for transforming objects
, however I find run
method name not really intuitive. In some other languages you have map
method name and it sounds much better to me. I think I'll give extension method a try.ribesg
09/16/2019, 12:14 PMmap
is a collection operation, doesn’t make sense for a single object to meandrzej
09/16/2019, 1:35 PMmap
of collection takes as argument a method for transforming single element of type T to single element of type R, so I'd say it works on single element.streetsofboston
09/16/2019, 1:41 PMmap
is used to map a container-of-T
to a container-of-R
and the container can be a List<T>
, and Optional<T>
, a Result<E, T>
, etc. Having a map
on a ‘naked’/unwrapped type, looks a bit off 🙂 .andrzej
09/16/2019, 1:43 PMrun
on single element?streetsofboston
09/16/2019, 1:49 PM(T) -> R
). I just write an extension function/property that is named toXXXX
or asXXXX
Stephan Schroeder
09/16/2019, 2:37 PMconvert
?!toXXX
a lot in the light of the well known toString
method.Burkhard
09/16/2019, 6:09 PMtoXXX
and asXXX
. The difference between the 2 is that toXXX
creates a new independent object while asXXX
only creates a view on the original (modifications are applied both 2 the original and the view no matter which is changed)Matej Drobnič
09/17/2019, 5:51 AMlet(User::toEntity)
instead of just .toEntity()
?ribesg
09/17/2019, 7:47 AMmap(User::toEntity)
instead of map { it.toEntity() }
all the time so I suppose they got confused maybe?Matej Drobnič
09/17/2019, 7:56 AMwasyl
09/17/2019, 8:03 AMmap
, since that’s what I usually do 🙂myanmarking
01/29/2020, 4:34 PM