0
votes

Official Ref says the default Visibility Modifier is public.

But from koan data classes it can be inferred that it is private.

Is it a contradiction? What is the default Visibility Modifier of property in kotlin?

---------The above is the initial question---------------

I didn't mix property and field up. But I did have confusion on how property is accessed.

To resolve my confusion, I actually should have asked the new question in edited title.

Self-answered below.

3
Properties are not fields.nhaarman

3 Answers

2
votes

What it the default Visibility Modifier for properties in kotlin?

It is public, as the docs say

Why are the fields not private

In this example the fields are immutable, so there are no setters defined automatically. The data class automatically has getters, and uses them, but it simplifies reading the code by not requiring them to be manually called.

Worked example

This code:

object X {
    data class Example(val a: String, val b: String)
    @JvmStatic
    fun main(args: Array<String>) {
        val e = Example("a", "b")
        println(e.a)
        println(e.b)
    }
}

The main method of this compiles to this (with checks and metadata removed):

public static final void main(String[] args) {
    X.Example e = new X.Example("a", "b");
    String var2 = e.getA();
    System.out.println(e.getA());
    var2 = e.getB();
    System.out.println(var2);
}

(Decompiled using IntelliJ IDEA)

5
votes

The default visibility for properties (and functions and classes, and...) is indeed public.

The Koan is a little confusing, because the Java class has private fields with public getters.
A property can be seen as the combination of field, a getter and an optional setter. The property in the Koan has a private backing field and a public getter.

If you for example write

val age = person.age

then Kotlin will basically generate a getAge() method of the Person class, that will be called internally. This method returns the field itself. It's also possible to add behavior to that getter. You can find more info in that in the documentation.

It's therefore not a contradiction, but a different concept.

0
votes

Property encapsulates backing field by defintion. Backing field is directly assigned only when being initialized. All accesses except initialization are done through accessors.

  • So the private modifier on field in Java is no longer needed in Kotlin.
  • And the public on getter and setter in Java is placed on property(actually, still for getter and setter) in Kotlin.

Therefore the omitted modifier is public and not private.