0
votes

I am very new to Kotlin, I was trying to migrate my java project to kotlin and I ran into a problem where I can't access implicit inherited members from my class.

In java I had a class called Robot.java which extends from TimedRobot.java and inside the TimedRobot.java there is a static member which is a double type

public class Robot extends TimedRobot {
}

TimedRobot.java from the library:

public class TimedRobot extends IterativeRobotBase {
    public static final double DEFAULT_PERIOD = 0.02;
    private double m_period = DEFAULT_PERIOD;
    ...
}

In the same package as the Robot.java I have a class called RobotConstants.java which holds some numbers. Even though there was no variable called DEFAULT_PERIOD in my Robot class I was still able to call it from outside like this:

public class RobotConstants {
    public static final int PERIOD_IN_MS = (int)(Robot.DEFAULT_PERIOD * 1000);
    ...
}

However I am not able to do that in kotlin.

My robot class in kotlin:

class Robot : TimedRobot() {
}

And I am unable to get the default period in my constants object in kotlin, it gives me a compile time error. Here is what I am trying to do:

object RobotConstants {
    const val PERIOD_Ms = (Robot.DEFAULT_PERIOD * 1000).toInt()
    ...
}
2
The static constants defined on a super type won't be accessible on the sub type in Kotlin (as opposed to Java). In your case, you could access DEFAULT_PERIOD only via TimedRobot - s1m0nw1
@s1m0nw1 thats a bummer to hear, but thank you for the clarification! - Mahim Arib

2 Answers

0
votes

You can either use the actual TimedRobot.DEFAULT_PERIOD constant or redefine it via a companion object:

class Robot : TimedRobot() {
    companion object {
        const val DEFAULT_PERIOD = TimedRobot.DEFAULT_PERIOD
    }
}

Another possibility is to represent these values as top level fields.

0
votes

If it's still bugs anyone like I did, the solution is putting the @JvmField annotation on the field