1

I have a Java file

public class Code {
    public static final int SUCCESS = 0;
    public static final int FAIL = 1;
}

I created a kotlin class that extends the Code class.

object ResponseCode : Code() {
    val SKU_STOCK_NOT_ENOUGH = 2000
}

I cannot call the statement, ResponseCode.SUCCESS, in other Kotlin function. What can I do to make kotlin class extend the Code class's static field.

2 Answers 2

1

In Kotlin, unlike Java, static members are not inherited by subclasses, though they can be called inside a subclass without specifying the base class name.

For this case, you can either call using the base class. Or:

object ResponseCode : Code() {
     val SKU_STOCK_NOT_ENOUGH = 2000
     val _SUCCESS = SUCCESS

}

One more option is declaring a method instead of a variable.

object ResponseCode : Code() {
    val SKU_STOCK_NOT_ENOUGH = 2000

    fun SUCCESS(): Int {
        return SUCCESS
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

there is no way to get static field from java class https://kotlinlang.org/docs/reference/java-interop.html#accessing-static-members

only way:

object ResponseCode : Code() {
    val SKU_STOCK_NOT_ENOUGH = 2000

    fun getSuccess() = SUCCESS
    fun getFail() = FAIL

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.