Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unresolved reference error while calling add method in Kotlin Set interface

Tags:

kotlin

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

like image 874
lujop Avatar asked Jan 27 '16 12:01

lujop


1 Answers

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.

like image 174
nhaarman Avatar answered Nov 03 '22 02:11

nhaarman