Hmhm, struggling to find a good name for a extensi...
# codereview
d
Hmhm, struggling to find a good name for a extension function that returns true when two lists have identical content (same references).
Copy code
fun <T> List<T>.isSameAs(other: List<T>): Boolean {
        if(size != other.size) return false

        forEachIndexed { index, element ->
            if(element !== other[index]) return false
        }

        return true
    }
Does anybody have an idea? Also maybe there might be a better way to check this?
s
I think that’s about as good as you can get it really - assuming order matters and
hashCode()
isn’t good enough for equality. You might consider adding an
if (this === other) return true
but it’s not strictly necessary
also maybe just call it
identicalTo()
as a personal point of style I don’t really like
forEach/forEachIndexed
for side-effect-ey operations that aren’t at the end of a call chain but that’s a nit more than anything in this case
b
m
contentEquals
is for Array, not List. Otherwise, I think they're the same, and you have just provided a meaningful name.
s
contentEquals
compares with `==
/
.equals()`, the requirement was identity equality of the elements
===
I think this is about as concise as I could get it
Copy code
infix fun <E> List<E>.identicalTo(other: List<E>): Boolean = when {
  this === other -> true
  size != other.size -> false
  else -> withIndex().all { (index, value) ->
    value === other[index]
  }
}
or this very mildly cursed looking thing
Copy code
infix fun <E> List<E>.identicalTo(other: List<E>): Boolean =
    other === this
        || other.size == size
        && withIndex().all { (index, value) ->
      value == other[index]
    }
d
Thank you all! Curious usecase and understandable, that this isn't in the standard lib
👍 1
The withIndex is smart!
🙏 1