3

I have this interface in Java:

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

And I want it to override in Kotlin code. I can't seem to do it.

Here's what I tried:

Here, I get an error that '<field> overrides nothing'

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

Here, I get the same error '<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?

sweet suman
  • 1,031
  • 8
  • 18
  • 1
    In case you need to implement many of such classes in Kotlin you may want to introduce your own Kotlin interface, which extends the Java one, so that you change the contract a bit, e.g. `interface KotlinErrorInfo : ErrorInfo { val _code : String; val _message : String; override fun getCode() = _code; override fun getMessage() = _message }`. This way the implementing classes can look something like this: `class ErrorInfoImpl(override val _code : String, override val _message : String) : KotlinErrorInfo`... – Roland Feb 10 '20 at 09:31

1 Answers1

1

The contract is to have getCode() and getMessage() methods only. 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
}
shazin
  • 21,379
  • 3
  • 54
  • 71