Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't isEmpty in Kotlin Collections a property?

Tags:

kotlin

I'm starting to learn Kotlin, and just noticed that Collections.isEmpty is a function, rather than a property. However, Collections.size is a property and not a function.

In most (all?) collections, I expect these two to be related semantically, and the implementation of isEmpty can simply be size === 0.

So... why isn't isEmpty a property? Is it simply a design bug?

like image 557
Ginandi Avatar asked Jun 01 '17 20:06

Ginandi


People also ask

How do I know if my Kotlin collection is empty?

Using isEmpty() function The standard solution to check if a list is empty in Kotlin is with the isEmpty() library function. It returns true if the list contains no elements, false otherwise.

What are the collections in Kotlin?

A collection is a group of related items, like a list of words, or a set of employee records. The collection can have the items ordered or unordered, and the items can be unique or not. You've already learned about one type of collection, lists. Lists have an order to the items, but the items don't have to be unique.


1 Answers

When deciding which methods of java.util.Collection will be properties in kotlin.collections.Collection the following considerations were taken into account:

  • both size and isEmpty can be qualified as properties according to Kotlin coding conventions, however size is inherent to the collection and isEmpty is just a derivative of the size property.
  • when implementing a collection one can override size val property with a var property (likely with a private setter), however the same is hardly ever needed for isEmpty.
  • exposing a method as a property requires additional methods generated in derived classes, better to keep their number as small as possible.
like image 67
Ilya Avatar answered Sep 29 '22 13:09

Ilya