Kotlin class 实现 Java 接口错误
Kotlin class implementing Java interface error
我有一个Java界面
public interface SampleInterface extends Serializable {
Long getId();
void setId(Long id);
}
和应该实现它的 Kotlin class
open class ClazzImpl() : SampleInterface
private val id: Unit? = null
fun getId(): Long? {
return null
}
fun setId(id: Long?) {
}
但是我得到一个编译错误:
Class ClazzImpl is not abstract and does not implement abstract member
public abstract fun setId(id: Long!): Unit defined in
com....SampleInterface
有什么想法吗?
您必须在 fun
之前添加 override
关键字:
override fun getId(): Long? {
return null
}
override fun setId(id: Long?) {
}
当您在 Kotlin 中实现接口时,您必须确保重写 class 的 inside 接口方法] 正文:
open class ClazzImpl() : SampleInterface {
private var id: Long? = null
override fun getId(): Long? {
return id
}
override fun setId(id: Long?) {
this.id = id
}
}
Egor和tynn的其他答案很重要,但是你在问题中提到的错误与他们的答案无关。
你必须先加上花括号。
open class ClazzImpl() : SampleInterface {
private val id: Unit? = null
fun getId(): Long? {
return null
}
fun setId(id: Long?) {
}
}
如果添加大括号,该错误就会消失,但您会收到如下新错误:
'getId' hides member of supertype 'SampleInterface' and needs
'override' modifier
现在,按照其他答案中的建议,您必须向函数添加覆盖修饰符:
open class ClazzImpl() : SampleInterface {
private val id: Unit? = null
override fun getId(): Long? {
return null
}
override fun setId(id: Long?) {
}
}
我有一个Java界面
public interface SampleInterface extends Serializable {
Long getId();
void setId(Long id);
}
和应该实现它的 Kotlin class
open class ClazzImpl() : SampleInterface
private val id: Unit? = null
fun getId(): Long? {
return null
}
fun setId(id: Long?) {
}
但是我得到一个编译错误:
Class ClazzImpl is not abstract and does not implement abstract member public abstract fun setId(id: Long!): Unit defined in com....SampleInterface
有什么想法吗?
您必须在 fun
之前添加 override
关键字:
override fun getId(): Long? {
return null
}
override fun setId(id: Long?) {
}
当您在 Kotlin 中实现接口时,您必须确保重写 class 的 inside 接口方法] 正文:
open class ClazzImpl() : SampleInterface {
private var id: Long? = null
override fun getId(): Long? {
return id
}
override fun setId(id: Long?) {
this.id = id
}
}
Egor和tynn的其他答案很重要,但是你在问题中提到的错误与他们的答案无关。
你必须先加上花括号。
open class ClazzImpl() : SampleInterface {
private val id: Unit? = null
fun getId(): Long? {
return null
}
fun setId(id: Long?) {
}
}
如果添加大括号,该错误就会消失,但您会收到如下新错误:
'getId' hides member of supertype 'SampleInterface' and needs 'override' modifier
现在,按照其他答案中的建议,您必须向函数添加覆盖修饰符:
open class ClazzImpl() : SampleInterface {
private val id: Unit? = null
override fun getId(): Long? {
return null
}
override fun setId(id: Long?) {
}
}