Luke
Luke

Reputation: 1306

How to open auto generated file level class

I am working on a project where I have some Kotlin-Java interoperability issue. What I discovered is that in Kotlin all class level functions are wrapped in an auto generated class which names are the same as fileName+kt. I want this class to be open. What decompiled bytecode shows is:

public final class ExampleAppKt

Is there a way to get rid of the final keyword?

Upvotes: 0

Views: 213

Answers (1)

Steyrix
Steyrix

Reputation: 3236

According to kotlinlang (Actually all the information is from there. I recommend to read it for more detailed info):

Kotlin has classes and their members final by default, which makes it inconvenient to use frameworks and libraries such as Spring AOP that require classes to be open. The all-open compiler plugin adapts Kotlin to the requirements of those frameworks and makes classes annotated with a specific annotation and their members open without the explicit open keyword.

You can enable all-open plugin via Gradle:

buildscript {
    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-allopen:$kotlin_version"
    }
}

apply plugin: "kotlin-allopen"

You can specify the annotation for classes to be compiled as open:

allOpen {
    annotation("com.my.Annotation")
    // annotations("com.another.Annotation", "com.third.Annotation")
}

If you use Maven, you can configure all-open as following:

<plugin>
<artifactId>kotlin-maven-plugin</artifactId>
<groupId>org.jetbrains.kotlin</groupId>
<version>${kotlin.version}</version>

    <configuration>
        <compilerPlugins>
            <!-- Or "spring" for the Spring support -->
            <plugin>all-open</plugin>
        </compilerPlugins>

        <pluginOptions>
            <!-- Each annotation is placed on its own line -->
            <option>all-open:annotation=com.my.Annotation</option>
            <option>all-open:annotation=com.their.AnotherAnnotation</option>
        </pluginOptions>
    </configuration>

    <dependencies>
        <dependency>
            <groupId>org.jetbrains.kotlin</groupId>
            <artifactId>kotlin-maven-allopen</artifactId>
            <version>${kotlin.version}</version>
        </dependency>
    </dependencies>
</plugin>

Upvotes: 1

Related Questions