hhg
hhg

Reputation: 687

Kotlin class implementing Java interface error

I've got a Java interface

public interface SampleInterface extends Serializable {
    Long getId();
    void setId(Long id);
}

and a Kotlin class that is supposed to implement it

open class ClazzImpl() : SampleInterface

private val id: Unit? = null

fun getId(): Long? {
    return null
}

fun setId(id: Long?) {

}

However I get a compilation error:

Class ClazzImpl is not abstract and does not implement abstract member public abstract fun setId(id: Long!): Unit defined in com....SampleInterface

any ideas what is wrong?

Upvotes: 6

Views: 7949

Answers (3)

tynn
tynn

Reputation: 39843

When you implement an interface within Kotlin, you have to make sure to override the interface methods inside of the class body:

open class ClazzImpl() : SampleInterface {

    private var id: Long? = null

    override fun getId(): Long? {
        return id
    }

    override fun setId(id: Long?) {
        this.id = id
    }
}

Upvotes: 2

Bob
Bob

Reputation: 13865

The other answers from Egor and tynn are important, but the error you have mentioned in the question is not related to their answers.

You have to add curly braces first.

open class ClazzImpl() : SampleInterface {

  private val id: Unit? = null

  fun getId(): Long? {
    return null
  }

  fun setId(id: Long?) {

  } 

}

If you add the curly braces, that error would have gone but you will get a new error like this:

'getId' hides member of supertype 'SampleInterface' and needs 'override' modifier

Now, as suggested in the other answers, you have to add override modifier to the functions:

open class ClazzImpl() : SampleInterface {

      private val id: Unit? = null

      override fun getId(): Long? {
        return null
      }

      override fun setId(id: Long?) {

      } 

}

Upvotes: 8

Egor Neliuba
Egor Neliuba

Reputation: 15054

You have to add the override keyword before fun:

override fun getId(): Long? {
    return null
}

override fun setId(id: Long?) {
}

Upvotes: 4

Related Questions