https://kotlinlang.org logo
Title
b

BMG

11/20/2018, 12:41 PM
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?
val updatedDataElementsOne = removeExtraElements(info)
val updatedDataElementsTwo = updateExistingElements(updatedDataElementsOne)
return populateEmptyElements(updatedDataElementsTwo)
b

bitkid

11/20/2018, 12:57 PM
info.filter{}.map{} or something like this?
a

Andreas Sinz

11/20/2018, 12:58 PM
You can define them as extension functions and use them like
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

BMG

11/20/2018, 1:05 PM
@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

Andreas Sinz

11/20/2018, 1:08 PM
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

BMG

11/20/2018, 1:13 PM
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

Andreas Sinz

11/20/2018, 1:15 PM
what about
list.map { //Update elements }
     .dropLast(10)
     .run { this + listOf(a, b, c) }
b

BMG

11/20/2018, 1:17 PM
Correct, but I have some business logic before doing each of them which I wanted to pull out as functions. Like,
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

dave08

11/21/2018, 3:17 AM
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.