If I use a Set interface reference and I try to call add method I get an unresolved reference error:
fun main(args : Array<String>) {
val set = HashSet<Integer>()
set.add(Integer(1)) //OK
val seti : Set<Integer> = HashSet<Integer>()
seti.add(Integer(2)) //FAILING: Unresolved reference to add**
}
I don't understand that behaivour. Java Set interface has an add method and I expected Kotlin one to be an extended version and not to had less methods.
PD1: I get the same error in Idea IDE or building with gradle. PD2: Using kotlin 1.0.0-beta-4584
Kotlin seperates Java's Set
interface into two interfaces: Set
and MutableSet
. The latter interface declares mutating methods such as the add
method you're looking for.
Generally, interfaces such as MutableSet
extend the Set
interface, and implementations like HashSet
implement the MutableSet
interface. The Set
interface can then be used to pass around a read-only instance, to help avoid common bugs from happening.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With