Kotlin类实现Java接口错误

我有一个Java界面

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

和一个应该实现它的Kotlin类

 open class ClazzImpl() : SampleInterface private val id: Unit? = null fun getId(): Long? { return null } fun setId(id: Long?) { } 

但是我得到一个编译错误:

类ClazzImpl不是抽象的,也不实现抽象成员public abstract fun setId(id:Long!):在com中定义的单元… SampleInterface

任何想法是什么错误?

Egor和tynn的其他答案很重要,但是你在问题中提到的错误与他们的答案无关。

你必须首先添加花括号。

 open class ClazzImpl() : SampleInterface { private val id: Unit? = null fun getId(): Long? { return null } fun setId(id: Long?) { } } 

如果你添加大括号,那么这个错误将会消失,但是你会得到一个像这样的新错误:

'getId'隐藏超类型'SampleInterface'的成员并需要'override'修饰符

现在,正如其他答案中所建议的那样,您必须为这些函数添加override override修饰符:

 open class ClazzImpl() : SampleInterface { private val id: Unit? = null override fun getId(): Long? { return null } override fun setId(id: Long?) { } } 

fun之前,您必须添加override关键字:

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

Kotlin中实现接口时,必须确保覆盖类体内的接口方法:

 open class ClazzImpl() : SampleInterface { private var id: Long? = null override fun getId(): Long? { return id } override fun setId(id: Long?) { this.id = id } }