They’re empty and what are they for?
Empty collections are something so unique so I do believe their usage must be quite limited. So I thought I really don’t have to make a post for it, but to get some Kotlin basics, I need to mention it anyway.
Okay, this time, let’s learn some basics of Kotlin’s emptyListOf(). Again, due to my limited time schedule, I really can’t write the explanations of them in my words, so I asked chatGPT, and here’s their answer to it.
The emptyList() function in Kotlin returns an empty list of a specific type. It is useful in situations where you need an empty list but you don’t want to initialize it with any elements.
It’s immutable, meaning it cannot be modified after it’s created, and it’s efficient as it doesn’t require allocating memory for any elements.
Using emptyList() instead of creating a new empty list with listOf() or mutableListOf() would be more efficient, as it returns a pre-existing singleton instance that can be used as a starting point for creating more lists.
It’s also useful in situations where you have a function which accepts a list as a parameter and you want to call that function with an empty list.
It can also be used in situations where you want to compare two lists and see if they are both empty or not.
chatGPT
And here are some of the codes I actually wrote and experimented with on my Linux environment.
emptyList<>()
fun emptyListLoop(empList: List<String>) {
for (word in empList) {
println(word)
}
}
fun main() {
val emptyList = emptyList<String>()
emptyList.add("One")
emptyList.add("Two")
emptyList.add("Three")
emptyListLoop(emptyList)
}
What's the file name? MyemptyList
MyemptyList.kt:9:15: error: unresolved reference: add
emptyList.add("One")
^
MyemptyList.kt:10:15: error: unresolved reference: add
emptyList.add("Two")
^
MyemptyList.kt:11:15: error: unresolved reference: add
emptyList.add("Three")
Other forms of empty lists:
val emptySet = emptySet<String>()
val emptySet = emptymap<Stringm Int>()