Question: why is `emptyList()` a generic function ...
# stdlib
n
Question: why is
emptyList()
a generic function that returns a
List<T>
, instead of a non-generic function that returns a
List<Nothing>
? (Or even a constant or object?)
d
So you can do
val list = emptyList<String>()
And also probably for consistency with the other list factory functions
n
👍
Although if it did return
List<Nothing>
and you did
val list = emptyList()
you’d still be able to pass
list
anywhere that expected a
List<String>
.
But static overloads would mess things up.
i
First, we prefer
Nothing
being explicitly mentioned in type arguments. Second, if we had
emptyList
without generic parameters, it would be inconsistent with
emptyMap
that cannot declare its return type so that it could be assignable to any
Map
type parametrization due to its
K
type parameter being invariant.
z
And it does return a static object of type
List<Nothing>
under the hood.
n
Yes, but the “nothingness” isn’t exposed at the API, which means you sometimes have to add an explicit generic type parameter to please the type inference, when actually it doesn’t need the parameter because it is is ignored under the hood.