Home > other >  When would MutableList.add() ever return false?
When would MutableList.add() ever return false?

Time:01-30

This Android Kotlin basics tutorial about lists says:

The add() function returns true if adding the element to the list succeeded, false otherwise

But on practice it seems the add() method either returns true when it succeeds or throws an exception if you try to pass an invalid parameter.

In what situation would the add() method return false? Could anyone give me an example?

CodePudding user response:

in the documentation said "@return true because the list is always modified as the result of this operation." so i understand that always is true and is not possible a false value

CodePudding user response:

The add function of a MutableList is inherited from the MutableCollection interface, which is why it must return a Boolean. The documentation for MutableCollection.add says this:

Return true if the element has been added, false if the collection does not support duplicates and the element is already contained in the collection.

Lists always support duplicates, which is why the documentation for MutableList.add specifies that this method always returns true. However, there are other types of collection, such as sets, that don't. When you try to add an item to a set, it will return false if the item was already in the set.

  •  Tags:  
  • Related