Home > Software engineering >  Kotlin - adding map function conditionally
Kotlin - adding map function conditionally

Time:12-13

I would like to feature toggle a map function on a list. I have a map that I would like to run only if the feature is on: So for something like this:

items
     .map { doTransformation(it) } 
     .map { runOnlyIfFeatureIsOn(it) }

Is there a way of adding the whole .map function conditionally in kotlin, so that it is only there if it is feature toggled?

CodePudding user response:

Maybe just do if in map? There is no problem with that:

val list = listOf(1, 2, 3)

    list
        .map { it * 2 }
        .map {
            if (featureIsOn) {
                runFeatureMapping(it)
            } else {
                it
            }
        }

CodePudding user response:

let() is handy for doing arbitrary processing in a pipeline, e.g.:

items
    .map{ doTransformation(it) } 
    .let{ if (someCondition) it.map{ runOnlyIfFeatureIsOn(it) } else it }

(For complex/costly conditions, this will be more efficient than putting the if inside the map call, as this'll only evaluate the condition once.)

CodePudding user response:

Using sequences:

var sequence = items.asSequence()
    .map { doTransformation(it) }

if (<feature_1_enabled>) {
    sequence = sequence.map { runOnlyIfFeature1IsOn(it) }
}

if (<feature_2_enabled>) {
    sequence = sequence.map { runOnlyIfFeature2IsOn(it) }
}

val result = sequence.toList()

Sequences are lazy-evaluated and should be used when mutliple operations (filter/map/etc) are applied

  • Related