There are 2 methods of creating empty collections,...
# announcements
a
There are 2 methods of creating empty collections, e.g. for a set: 1.
emptySet()
2.
setOf()
I know these two are equivalent (implementation is identical), but what is the more idiomatic Kotlin way? Is there any reason why 2 solutions exist for the same issue? I know this question might sound silly but we have a code base where both ways are used and want to get rid of one of them once and for all.
h
setOf takes a vararg which is why you can ommit any params, but if your intention is to create a set without any elements, emptySet is probably the correct way
m
use setOf() wherever you are actually using something where you don't know if the standard size of that set might be bigger than 0 in the future, so in the future you could theoretically have: setOf("someValue", "someOtherValue") emptySet() is an explicit empty set. Use this if this is truly the intention of your logic.
a
@Hanno nope, here is setOf implementation:
Copy code
@kotlin.internal.InlineOnly
public inline fun <T> setOf(): Set<T> = emptySet()
m
that's just filler code because varargs takes additional bytes/logic. This ensures that setOf without arguments is still as fast as possible
m
@Michael de Kaste
setOf
creates a read only set, so it won't get bigger in the future.
m
it's the same reason why, in java, I know that some standard libraries they make functions for every size up to 10 or something
@marstran, yes I know. I used the example to show that maybe you don't know in the future of the intention of the set would be to always be empty at first. e.g; val invalidStrings = setOf() maybe in the future you might want to change this standard set to setOf("thisIsInvalid", "thisToo")
d
I would discourage the use of
setOf()
in general.
👍 1
Only when you're doing something like
Copy code
val someSpecialStrings = setOf(
)
The problem is that without any parameters, the element type can't be inferred, so there's little point having this function.
d
Function should be
Copy code
setOf(first: T, vararg ensuing: T)
Dont know why they decided against it. Other than that: emptySet() is most likely a fallback of some sort. So best be explicit and call it emptySet(). The empty immedeately conveys the meaning ``````
👍 1