Hello, World! Am I the only one who finds this is...
# stdlib
b
Hello, World! Am I the only one who finds this is kind of missing?
Copy code
fun <E> MutableCollection<E>.set(elements: Collection<E>) {
    clear()
    addAll(elements)
}

fun <E> MutableCollection<E>.set(vararg elements: E) = set(elements.asList())
Similarly,
Copy code
fun <K, V> MutableMap<K, V>.set(from: Map<K, V>) {
    clear()
    putAll(from)
}

fun <K, V> MutableMap<K, V>.set(vararg pairs: Pair<K, V>) {
    clear()
    putAll(pairs)
}
d
set
is confusing name to me. Since it's used for other stuff. Like setting an element in a list or map.
b
Maybe
reset
then?
replaceAll
would make sense, but that already exists on Map, with a different meaning
e
depends on your use case… why not just use a
var Collection<E>
?
if it's being shared among multiple classes… consider re-structuring it to designate a single owner for the mutability
b
My use case is for APIs exposing val MutableCollections. Maybe it is not that common, but for instance the Android Gradle plugin does this for
resourceConfigurations
and
manifestPlaceholders
(maybe
replaceBy
or
replaceAllBy
would be a good name)
e
ah, understandable in that case. I don't think there's a good name for it -
set
would match the
Provider.set
, but can be confused with
MutableList.set(index, elem)
,
replace
is also about items…
a
Ideally Kotlin should have an assignment operator which can be overloaded, for example:
Copy code
operator fun MutableSet<T>.assign(another:Collection<T>) {
  clear()
  addAll(another)
}
To be used as such:
Copy code
val set = mutableSetOf(1, 2, 3)
set = setOf(12,13,16)
1
e
that would make it all the more confusing in case of
var _: MutableCollection<*>
- operator overloading isn't the right answer here, IMO
1
a better naming scheme could use the word "content" or "values" to make it clear what is being affected, e.g.
Copy code
fun <T> MutableCollection<T>.setAllValues(values: Iterable<T>)
fun <T> MutableCollection<T>.setValues(vararg values: T)
👍 1
d
Kotlin isn't C++ sadly.
😱 1