Why is this Kotlin class property not public?
Asked Answered
B

1

5

I've got an app that is regularly using classes written in Kotlin which are accessed by other classes and their methods written in Java.

I had the following class in Java:

public class MyDataClass {
    public String color;
    public String action;
}

I've decided to move it to Kotlin:

class MyDataClass {
    var color: String = ""
    var action: String = ""
}

Upon recompiling, I'm now getting the following error message:

/myPath/MyApp.java:[93,20] color has private access in myapp.command.MyDataClass

I get a similar error for action.

Per the Kotlin reference, the default visibility modifier for class and properties (and a bunch of other things) is public.

Why are these properties being treated as private?

Brunt answered 11/3, 2019 at 16:39 Comment(1)
Because it's a private field with a public getter and a public setter. You cannot access fields directly in Kotlin, everything is properties.Recaption
R
9

Because it's a private field with a public getter and a public setter. You cannot access fields directly in Kotlin, everything is properties.

Refer to: https://kotlinlang.org/docs/reference/properties.html#backing-fields

Recaption answered 11/3, 2019 at 16:44 Comment(5)
Thanks. What do you mean by "everything is properties"?Brunt
If you declare the var something: String, then it will always be "private field + public accessors". In Java, people typically called these "properties", or at least that's how I remember.Recaption
Good answer; minor addition: you can mark a property as @JvmField to have it compile to a field.Sublunary
Ah yes, that is true. I'm not sure why I forgot to mention that.Recaption
@Recaption Thank you very much for your comment , adding JvmField annotaion solve problem that cause headache for meHoroscopy

© 2022 - 2024 — McMap. All rights reserved.