How do I remove the `is` prefix for boolean properties from Java classes?

I have a Java class from an external library that I need to extend and use in my local kotlin project:

class Profile {
    private boolean activeByDefault;
    public boolean isActiveByDefault() { return activeByDefault; }
    public void setActiveByDefault(boolean activeByDefault) { this.activeByDefault = activeByDefault; }

Why do I have to access this property by the name of the getter? profile.isActiveByDefault

If the above class were written in kotlin, The behavior would be different: profile.activeByDefault

class Profile(var activeByDefault)

Why does kotlin force behavior onto existing Java classes that it doesn’t force onto itself? The inconsistency is confusing engineers that use my libraries.

1 Like

The simple and obvious answer is that the field is declared private in your Java class, and the property is declared public in your Kotlin class.

If you want your Java field to be accessed directly, you need to declare it publicly. Of course, that would break encapsulation and reveal implementation details.

Note that a public Kotlin property does not come with the same problems as a public field in Java. Even if a Kotlin property is declared public, the underlying implementation behind that property can later be changed without breaking compatibility with legacy clients.

1 Like

Add to that the fact that Kotlin will actually also use the getter/setter internally in the class in all cases (unless it optimizes away trivial getters/setters). So in Java the correct way to get the value is still isActiveByDefault().