6

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?

0

3 Answers 3

8

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?) {

      } 

}
Sign up to request clarification or add additional context in comments.

Comments

4

You have to add the override keyword before fun:

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

override fun setId(id: Long?) {
}

1 Comment

Looks like the docs are pretty explicit indeed: "[...]we stick to making things explicit in Kotlin. And unlike Java, Kotlin requires explicit annotations for overridable members (we call them open) and for overrides[...]"
2

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
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.