Home > database >  Kotlin list removeAll is not working with a list
Kotlin list removeAll is not working with a list

Time:11-18

Why Kotlin list removeAll doesnt not work in this example:

orderList.addAll(allProducts)
orderList.removeAll(allProducts)

The code above will add the products but not remove them. orderList is a mutableList

Product:

class Product : EmbeddedRealmObject {
var name: String = ""
var category: String = ""
var productDescription: String? = ""
var price: Float = 0F
var imagine: String? = null

}

CodePudding user response:

It's not working because you don't have proper equals() and hashcode() functions defined for your class Product. removeAll works by finding elements in your collection where an equals() equality check returns true with elements in the collection you pass to it. It also uses a Set under the hood to optimize this process, so hashcode() must be appropriately defined in relation to equals().

You can generate equals() and matching hashcode() functions using the options in the IDE, or you can define this as a data class instead of a plain class. data classes automatically have proper equals() and hashcode() that use all the properties that are defined in the primary constructor.

  • Related