Home > Software design >  Implementation method according to the access limiter of anonymous object
Implementation method according to the access limiter of anonymous object

Time:10-15

When an anonymous object is public, it is simply implemented as an object return, but when it is private, it is returned as a type-cast object. look at the Kotlin code below.

private fun foo() = object {
    val x: String = "x"
}

fun bar() = object {
    val x: String = "x"
}

When this code is decompiled into Java, it changes like this:

private static final <undefinedtype> foo() {
    return (<undefinedtype>)(new Object() {
        @NotNull
        private final String x = "x";

        @NotNull
        public final String getX() {
            return this.x;
        }
    });
}

@NotNull
public static final Object bar() {
    return new Object() {
        @NotNull
        private final String x = "x";

        @NotNull
        public final String getX() {
            return this.x;
        }
    };
}

Therefore, when you try to use the code, only the private anonymous object can access x.

code

So, why do each access modifiers have different implementations?

CodePudding user response:

That is how language defines the semantics of anonymous objects.

Type of an anonymous object is only usable in the declaring scope, when you use public modifier, anonymous object escapes the current scope and is cast to Any (implicit super type). since Any doesn't have any property x, you can't access it. on the other hand when you use private modifier you make sure that it doesn't escape the current scope.

From the Kotlin language specification

The main difference between a regular object declaration and an anonymous object is its type. The type of an anonymous object is a special kind of type which is usable (and visible) only in the scope where it is declared. It is similar to a type of a regular object declaration, but, as it cannot be used outside the declaring scope, has some interesting effects.

When a value of an anonymous object type escapes current scope:

  1. If the type has only one declared supertype, it is implicitly downcasted to this declared supertype;
  2. If the type has several declared supertypes, there must be an implicit or explicit cast to any suitable type visible outside the scope, otherwise it is a compile-time error.

Note: in this context “escaping current scope” is performed immediately if the corresponding value is declared as a non-private global or classifier-scope property, as those are parts of an externally accessible interface.

  • Related