What's the intended use of @JvmSynthetic in Kotlin?

后端 未结 2 621
一生所求
一生所求 2020-12-07 00:34

I have come across the @JvmSynthetic annotation in kotlin-stdlib, and I\'m wondering what it is for, but, unfortunately, it is undocumented. (UPD: it was at that moment)

2条回答
  •  独厮守ぢ
    2020-12-07 01:10

    In plain Java, synthetic methods are generated by the javac compiler. Normally the compiler must create synthetic methods on nested classes, when fields specified with the private modifier are accessed by the enclosing class.

    Given the following class in java:

    public final class SyntheticSample
    {
        public static void main(final String[] args)
        {
            SyntheticSample.Nested nested = new SyntheticSample.Nested();
            out.println("String: " + nested.syntheticString);
        }
    
        private static final class Nested
        {
            private String syntheticString = "I'll become a method!";
        }
    }
    

    when the SyntheticSample class accesses the nested.syntheticString field, it is indeed calling a static synthetic method generated by the compiler (named something like access$100).

    Even if Kotlin exposes a @JvmSynthetic annotation that is able to "force" the creation of synthetic methods, I advice to not using it in normal "user" code. Synthetic methods are low-level tricks made by the compiler, and we should never rely on such things in everyday code. I think it's there to support other parts of the standard library, but you should ask the JetBrains guys directly if you're curious (try on the official Kotlin Discussion Forum)

提交回复
热议问题