Jukka Siivonen
09/07/2021, 1:36 PMJukka Siivonen
09/07/2021, 1:37 PMval results = <get collection>
return results
.filter { it.matchType == MatchType.EXACT }
.also {
// Do logging
}
.singleOrNull()
?: results
.filter { it.matchType == MatchType.PARTIAL }
.also {
// Do logging
}
.singleOrNull()
Jukka Siivonen
09/07/2021, 1:37 PMsbyrne
09/07/2021, 1:46 PMchristophsturm
09/07/2021, 2:35 PMJukka Siivonen
09/07/2021, 5:50 PMJukka Siivonen
09/07/2021, 5:54 PMTobias Suchalla
09/08/2021, 9:27 AMval results = getCollection().groupBy { it.matchType }
val matches = results[MatchType.EXACT] ?: results[MatchType.PARTIAL]
// log matches
return matches?.firstOrNull()
If you want exactly one EXACT
match or else exactly one PARTIAL
match:
val results = getCollection().groupBy { it.matchType }
val match = results[MatchType.EXACT]?.singleOrNull()
?: results[MatchType.PARTIAL]?.singleOrNull()
// log match
return match
I'd say that both do look clearer than you original code. Can't comment on performance though.smichel17
09/09/2021, 1:39 PMkt
val results = <get collection>
return results.singleOfType(MatchType.EXACT)
?: results.singleOfType(MatchType.PARTIAL)
private fun <T: HasMatchType>Collection<T>.singleOfType(type: MatchType): T? {
return this
.filter { it.matchType == type }
.also {
// Do logging
}
.singleOrNull()
}
However, a word of warning: only do this if you're certain that these parts aren't incidental duplication. It's easy to turn a code base into spaghetti trying to remove de-duplication when actually you're coupling pieces of functionality that are just similar, not the same. Which becomes a giant pain when you need to change one of them later and you need to un-tangle them, first :PJukka Siivonen
09/09/2021, 5:39 PMJukka Siivonen
09/09/2021, 5:45 PM