I have code that combines and deduplicates two arrays. When duplicates are found, it drops the corresponding items of the second array.
fun combineAndDedupe(fromMainSupplier: List<Book>, fromSecondarySupplier: List<Book>): List<Book> {
val isbnsFromMain = fromMainSupplier.map { it.isbn }
return fromMainSupplier + fromSecondarySupplier.filter { it.isbn !in isbnsFromMain }
}
I have been asked write a log-statement if any books have been filtered out, listing all affected ISBN's. I am struggling to implement this in a way that feels "Kotliny". It's too verbose, too long, too hard to read. Is there a more elegant way? I often encounter this problem where the original code is reasonably elegant, but once you add a log-statement, you are writing Java 7 again.
One of my more verbose attempts:
private fun combineAndDedupe(fromMainSupplier: List<Book>, fromSecondarySupplier: List<Book>): List<Book> {
val isbnsFromMain = fromMainSupplier.map { it.isbn }
val isbnsFromSecondary = fromSecondarySupplier.map { it.isbn }
val isbnsToRemove = isbnsFromSecondary.filter { it in isbnsFromMain }
if (isbnsToRemove.isNotEmpty()) {
val isbnsString = isbnsToRemove.joinToString(",")
logger.info(
"Removing books from secondary supplier that are already present in main supplier: ${isbnsString}"
)
}
return fromMainSupplier + fromSecondarySupplier.filter { it.isbn !in isbnsToRemove }
}