Can someone explain to me, why hashCode is differe...
# getting-started
n
Can someone explain to me, why hashCode is different for these
s1
,
s2
sequences? I would expect it to be the same as in lists.
Copy code
// 1
    val s1 = sequenceOf(1, 2, 3)
    val s2 = sequenceOf(1, 2, 3)
    s1.hashCode() == s2.hashCode() // false - why?
    
    // 2
    val l1 = sequenceOf(1, 2, 3).toList()
    val l2 = sequenceOf(1, 2, 3).toList()
    l1.hashCode() == l2.hashCode() // true - fine as lists contain the same items
e
sequence is an abstraction over iterator. it is not expected to be a persistent collection - use collection for that
c
Sequences cannot go through their elements (what if the sequence was infinite?), so the hash cannot depend on the elements.
e
even if it out were finite, a sequence may be iterable only once. so again the hash code can't use the elements
2
n
@ephemient can you please elaborate on the last answer?
Don’t I iterate twice over the same sequence here 🤔
Copy code
val s1 = sequenceOf(1, 2, 3)
    s1.forEach { println(it) }
    s1.forEach { println(it) }
e
some sequences, not all
Copy code
var i = 0
val s = generateSequence { ++i }.take(3)
s.forEach {}
s.forEach {}
throws
as does
Copy code
listOf(1, 2, 3).iterator().asSequence()
that's basically the difference between Iterable and Sequence. the interface is similar but the expectations are different
👍 1