https://kotlinlang.org logo
#getting-started
Title
# getting-started
t

tseisel

10/12/2020, 2:09 PM
Is there a Kotlin library (or at least a JVM library) to compute differences between 2 `List`s ? Something like:
Copy code
fun <T> listDiff(original: List<T>, revised: List<T>): List<DiffOp<T>>

sealed class DiffOp<T> {
  class Add<T>(val element: T, val index: Int) : DiffOp<T>()
  class Remove<T>(val element: T, val index: Int) : DiffOp<T>()
}
I find myself needing this kind of feature quite often. I've searched the web like crazy, but it seems that Myer's Diff Algorithm has only been implemented for diffing text, not collections. Swift's standard library implements it as CollectionDifference. Maybe this could be a nice library to have for Kotlin Multiplatform ?
v

Vampire

10/12/2020, 2:30 PM
Depending on what exactly you need, this might already be enough:
Copy code
val x = listOf(1, 2, 3)
val y = listOf(2, 4, 5)
val added = y - x
val removed = x - y
t

tseisel

10/12/2020, 2:33 PM
Unfortunately, I really need to find what patch operations (add at X, remove at Y) are to be applied to transform the first list to the second. Android RecyclerView has DiffUtil to cover UI usecases, but now I need it for a non-Android project ...
Maybe I'll have to spend some time on Myer's papers and build a library for MPP, solving that problem once for all platforms! 🙂
a

arekolek

10/12/2020, 2:34 PM
I used `SequenceMatcher` in python, turns out somebody implemented it in Kotlin https://github.com/mhv2109/difflib
v

Vampire

10/12/2020, 2:54 PM
Isn't that just giving a similarity value?
a

arekolek

10/12/2020, 5:25 PM
that was just the example in readme, looks like they implemented everything though, in particular getOpcodes()
2 Views