https://kotlinlang.org logo
#codereview
Title
# codereview
d

Daniel

03/25/2020, 10:15 PM
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

Shawn

03/25/2020, 10:31 PM
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

bitnot

03/26/2020, 9:55 AM
m

Mike

03/26/2020, 12:33 PM
contentEquals
is for Array, not List. Otherwise, I think they're the same, and you have just provided a meaningful name.
s

Shawn

03/26/2020, 2:55 PM
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

Daniel

03/26/2020, 5:58 PM
Thank you all! Curious usecase and understandable, that this isn't in the standard lib
👍 1
The withIndex is smart!
🙏 1