Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 318
hhg Avatar asked Aug 21 '17 15:08

hhg


2 Answers

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

      } 

}
like image 159
Bob Avatar answered Nov 01 '22 10:11

Bob


You have to add the override keyword before fun:

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

override fun setId(id: Long?) {
}
like image 29
Egor Neliuba Avatar answered Nov 01 '22 08:11

Egor Neliuba