简体   繁体   English

在 Kotlin 中仅使用 getter 覆盖 Java 接口

[英]Override Java interface with only getters in Kotlin

I have this interface in Java:我在 Java 中有这个接口:

public interface ErrorInfo {
  String getCode();
  String getMessage();
}

And I want it to override in Kotlin code.我希望它在 Kotlin 代码中覆盖。 I can't seem to do it.我好像做不到

Here's what I tried:这是我尝试过的:

Here, I get an error that '<field> overrides nothing'在这里,我收到一个错误,即'<field> overrides nothing'

class ErrorInfoImpl(
  override val code: String,
  override val message: String
) : ErrorInfo

Here, I get the same error '<field> overrides nothing'在这里,我收到相同的错误'<field> overrides nothing'

class ErrorInfoImpl(
  code: String,
  message: String
) : ErrorInfo {
   override val code: String = code
   override val message: String message
}

This code works, but it looks dirty:此代码有效,但看起来很脏:

class ErrorInfoImpl(
  private val __code: String,
  private val __message: String
) : ErrorInfo {
    override fun getCode(): String = __code
    override fun getMessage(): String = __message
}

Are there better ways to do this?有没有更好的方法来做到这一点?

The contract is to have getCode() and getMessage() methods only.契约是只有getCode()getMessage()方法。 What it returns is up to implementing class.它返回什么取决于实现类。 The cleanest in this case is following:在这种情况下,最干净的如下:

class ErrorInfoImpl(
  private val code: String,
  private val message: String
) : ErrorInfo {
    override fun getCode(): String = code
    override fun getMessage(): String = message
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM