Sure, it may work fine in some cases. And then in ...
# announcements
k
Sure, it may work fine in some cases. And then in others it doesn't, eg.
Copy code
data class Foo(var x: Int)

fun main(args: Array<String>) {
    val f = Foo(3)
    val s = mutableSetOf(f)
    f.x = 7
    println(s == setOf(Foo(7)))
}
on try.kotlinlang.org.
a
Set != MutableSet
interesting, it works with
Set
, but not with
MutableSet
🤔
p
it works with
Set
on JVM but not on JavaScript 🙃
k
Aren't they both
HashSet
behind the scenes?
p
No
public fun <T> setOf(element: T): Set<T> = java.util.Collections.singleton(element)
Copy code
public fun <T> mutableSetOf(vararg elements: T): MutableSet<T> = elements.toCollection(LinkedHashSet(mapCapacity(elements.size)))
k
Well doesn't really matter even, the point is that it sometimes randomly fails.
p
👍
k
I'll spend some time finding a hashset - hashset equals that fails simple smile
p
Copy code
data class Foo(var x: Int)

fun main(args: Array<String>) {
    val f = Foo(3)
    val g = Foo(4)
    val s = setOf(f,g)
    f.x = 7
    println(s == setOf(Foo(7), Foo(4)))
}
👍 1
that fails
I would expect it to succeed every time on JVM for a single element set and fail for multielement sets
d
I once submitted a bug for java.util.HashMap because if you mutate the keys, you can't remove it with the iterator. I argued that if you iterate all the elements and call remove for each one, the map should be empty (assuming no concurrent stuff going on) no matter what. I guess it's similar to this - you shouldn't mutate elements, but to what extent should a collection function if it does happen? Bug was fixed - there was another reason - but still.
There are some things that might still work if you mutate object in the set - for example it might still be returned from the iterator. But
contains
check breaks completely.
Why do you think it would work for single element sets?
p
because the implementation is
public fun <T> setOf(element: T): Set<T> = java.util.Collections.singleton(element)
d
ah, makes sense
p
with this implementation it doesn’t have much choice
d
singleton
method name always annoys me
👍 1