Of course! The original code is a concise and efficient Kotlin idiom, but its logic can be a bit dense. Refactoring it to separate the filtering and mapping steps can definitely improve readability.
Here are a few refactored versions, with the first one being the most recommended.
Recommended Refactoring: withIndex(), filter, and associate
This approach is more declarative and clearly separates the logic into "what to keep" (filter) and "how to transform it" (associate). associate is the perfect tool for building a map directly from a collection.
kotlin
reorderedQuestions
.withIndex() // Step 1: Pair each question with its new index.
.filter { (index, question) ->
// Step 2: Keep only the items whose position has changed.
val newPosition = index + 1
val oldPosition = initialPositions[question.id]
newPosition != oldPosition
}
.associate { (index, question) ->
// Step 3: Create a map from the filtered items.
question.id to (index + 1)
}
Why this is more readable:
Separation of Concerns: The filter block is solely responsible for the conditional logic, while the associate block is responsible for creating the final Map entry. This makes the purpose of each step clearer.
Explicit Naming: The intermediate newPosition and oldPosition variables inside the filter lambda make the comparison explicit and self-documenting.
Avoids null: It completely avoids the if/else -> null pattern, which was the core of your request.
associate is a Perfect Fit: Using associate is more idiomatic and efficient for creating a map than map { ... }.toMap() because it builds the map directly without creating an intermediate List of Pairs.
Alternative 1: Using filterIndexed
This is very similar to the above but uses filterIndexed to combine steps 1 and 2. It's slightly more concise.
kotlin
reorderedQuestions
.filterIndexed { index, question ->
// Filter based on both index and item
val newPosition = index + 1
newPosition != initialPositions[question.id]
}
.associate { question ->
// Problem: The index is lost here! We need it again.
// This approach doesn't work directly.
// You would have to re-calculate the index, which is inefficient.
The first recommended approach using .withIndex() is superior because it preserves the index through the filter operation, making it available for the final associate step.
Alternative 2: The Imperative Approach (for ultimate clarity)
Sometimes, a simple forEach loop is the most readable option, especially if the functional chain becomes too complex. It's not as "Kotlin-idiomatic" as a functional chain, but it's very explicit and easy to debug.
kotlin
val positionChanges = mutableMapOf<QuestionId, Int>()
reorderedQuestions.forEachIndexed { index, question ->
val newPosition = index + 1
if (newPosition != initialPositions[question.id]) {
positionChanges[question.id] = newPosition
}
}
// The result is in the `positionChanges` map
Why this can be good:
Simplicity: No complex lambdas or chained calls. The logic is step-by-step and easy to follow.
Efficiency: Very high performance, as it's a single pass over the list with no intermediate collections created.
Creates an intermediate Iterable<IndexedValue> (very lightweight).
Original mapIndexedNotNull
Very concise and efficient, common Kotlin idiom.
Logic is dense, combines filtering and mapping, uses null.
Imperative forEachIndexed
Extremely clear and simple, highly efficient.
Requires an external mutable variable, not a functional expression.
For your goal of improved readability by separating filtering, the withIndex().filter().associate() pattern is the best choice. It balances the expressiveness of Kotlin's functional API with clear, understandable code.