I need to do a set of list operations and I want t...
# codereview
b
I need to do a set of list operations and I want those methods to be pure with taking List as input and giving List as output and they have to be chained. Can this be improved?
Copy code
val updatedDataElementsOne = removeExtraElements(info)
val updatedDataElementsTwo = updateExistingElements(updatedDataElementsOne)
return populateEmptyElements(updatedDataElementsTwo)
b
info.filter{}.map{} or something like this?
a
You can define them as extension functions and use them like
Copy code
fun List<T>.removeExtraElements(): List<T> {
    //Do work
    //Return new list
}

fun List<T>.updateExistingElements(): List<T> {
    //Do work
    //Return new list
}
//usage
list.removeExtraElements().updateExistingElements()
b
@bitkid I couldn’t do
populate
operation in that chain where I need to add some elements at the end of the list. @Andreas Sinz I assumed that extensions were overkill for this. But I really like the chaining ability it gives!
a
Just try to limit the number/the visibility of extensions on common types like
List<T>
, otherwise you end up with a huge list of entries in code completion
👍 1
what actions do you have to do on the list? maybe we can work something out with standard extension functions
b
Sure, I made them
private
extensions. I have mainly three operations with some business logic, 1) update elements 2) remove elements at the end (
dropLast
) 3) add some elements at the end
a
what about
Copy code
list.map { //Update elements }
     .dropLast(10)
     .run { this + listOf(a, b, c) }
b
Correct, but I have some business logic before doing each of them which I wanted to pull out as functions. Like,
Copy code
list
.mapIndexed {
   // 10 lines of code which modifies each element
}
.dropLast {
   calculatedNumberOfElementsToRemove()
}
.run {
// 10 lines of code to add new elements
}
Now I’m thinking I can just pull those 10 lines of code as a function instead of extension
d
If the function has the exact same inputs and outputs as
mapIndexed
say, then you could just call it
mapIndexed(businessLogicObjInstance::myFunction)
. You then avoid the extra lambda.