Dmitry Shut
Dmitry Shut

Reputation: 21

Kotlin noarg plugin not initializing default values

Hello I have the following code(jdk)

build.gradle.kts

plugins {
    kotlin("jvm") version "1.7.10"
    id("org.jetbrains.kotlin.plugin.noarg") version "1.7.10"
    application
}

noArg {
    annotation("com.MyAnnotation")
}

Classes and annotation

annotation class MyAnnotation

@MyAnnotation
class A(
    var a: String = java.util.UUID.randomUUID().toString()
)

@MyAnnotation
class Ab (
    var a: String = java.util.UUID.randomUUID().toString(),
    var b: String
)

When I initialize A and Ab classes through Java with no args

new A() and new Ab()

In class A field a is initialized, but in class Ab it is not Decompiled constructors of A and Ab

public A() {
    this(null, 1, null);
}
public Ab() {}

But when I use properties instead of constructors

@MyAnnotation
class A {
    var a: String = java.util.UUID.randomUUID().toString()
}
@MyAnnotation
class Ab {
    var a: String = java.util.UUID.randomUUID().toString()
    lateinit var b: String
}

Everything works ok and decompiled constructors is

public A() {
    Intrinsics.checkNotNullExpressionValue(UUID.randomUUID().toString(), "randomUUID().toString()");
    this.a = UUID.randomUUID().toString();
}
public Ab() {
    Intrinsics.checkNotNullExpressionValue(UUID.randomUUID().toString(), "randomUUID().toString()");
    this.a = UUID.randomUUID().toString();
}

What I'm doing wrong or it is an issue in Kotlin?

Upvotes: 2

Views: 406

Answers (1)

Alexey Nurmukhametov
Alexey Nurmukhametov

Reputation: 23

This issue is similar to No-Arg plugin causing lazy delegate to not be initialized and throw a NullPointerException. Based on the answer there you just need to add one line to your build.gradle.kts:

noArg {
    annotation("com.MyAnnotation")
    invokeInitializers = true
}

Additional info can be found on Kotlin webpage: https://kotlinlang.org/docs/no-arg-plugin.html

Upvotes: 0

Related Questions