https://kotlinlang.org logo
Title
k

karelpeeters

09/27/2018, 5:25 PM
Sure, it may work fine in some cases. And then in others it doesn't, eg.
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

Andreas Sinz

09/27/2018, 5:27 PM
Set != MutableSet
interesting, it works with
Set
, but not with
MutableSet
🤔
p

pavel

09/27/2018, 5:33 PM
it works with
Set
on JVM but not on JavaScript 🙃
k

karelpeeters

09/27/2018, 5:35 PM
Aren't they both
HashSet
behind the scenes?
p

pavel

09/27/2018, 5:35 PM
No
public fun <T> setOf(element: T): Set<T> = java.util.Collections.singleton(element)
public fun <T> mutableSetOf(vararg elements: T): MutableSet<T> = elements.toCollection(LinkedHashSet(mapCapacity(elements.size)))
k

karelpeeters

09/27/2018, 5:37 PM
Well doesn't really matter even, the point is that it sometimes randomly fails.
p

pavel

09/27/2018, 5:37 PM
👍
k

karelpeeters

09/27/2018, 5:37 PM
I'll spend some time finding a hashset - hashset equals that fails 😒imple_smile:
p

pavel

09/27/2018, 5:40 PM
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

Dico

09/27/2018, 5:41 PM
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

pavel

09/27/2018, 5:44 PM
because the implementation is
public fun <T> setOf(element: T): Set<T> = java.util.Collections.singleton(element)
d

Dico

09/27/2018, 5:44 PM
ah, makes sense
p

pavel

09/27/2018, 5:44 PM
with this implementation it doesn’t have much choice
d

Dico

09/27/2018, 5:45 PM
singleton
method name always annoys me
👍 1