Detailed Explanation of Kotlin in Gradle without Parameter (no arg) Compiler Plug in

  • 2021-11-13 18:08:52
  • OfStack

1. Preface

Recently, I am writing a back-end project with Kotlin+Spring Boot. The entity class habitually uses data class in Kotlin, but Spring requires a constructor without parameters, otherwise java. sql. SQLDataException may be thrown. To enable data class to generate a parameterless constructor, there are two ways:

1. Assign default values to every 1 parameter in the constructor of data class. For example:


data class User(
  @TableId(value = "id", type = IdType.AUTO)
  var id: Int?=-1,
  var userName: String?=null, // User name 
  var age: Int?=null, // Age 
  var password: String?=null, // Password 
  var name: String?=null, // Name 
  var email: String?=null  // Mailbox 
) : Serializable

2. Use the non-parametric compiler plug-in no-arg. Let's take a look at this method.

2. Specific steps

2.1 Adding plug-in dependencies
First of all, we need to add the dependency of no-arg plug-in to build. gradle of the project. The version is the same as version 1 of Kotlin:


plugins {
     ... 
  id "org.jetbrains.kotlin.plugin.noarg" version "1.3.41"
}

I'm using the plugins format. If you're using an buildscript block, you can add it like this:


buildscript {
  dependencies {
    classpath "org.jetbrains.kotlin:kotlin-noarg:1.3.41"
  }
}

apply plugin: "kotlin-noarg"

2.2 Specify a list of non-parametric comments

To tell the truth, this step is not easy to understand when reading the official documents. Here, I only describe my experience after my own practice. First, create an annotation class, which can be named NoArg:


annotation class NoArg

Then the most critical step is to go back to the build. gradle file of the project and add a list of non-parametric comments:


noArg {
  annotation("com.lindroid.projectname.annotation.NoArg")
}

The path in annotation is the package directory where we created the NoArg annotation class. Path 1 must be written well, don't make mistakes! At this point, the parametric plug-in is already configured. We can prefix data class with the @ NoArg annotation so that the compiler can generate a parameterless constructor for it. Examples of use are as follows:


@NoArg
data class User(
  @TableId(value = "id", type = IdType.AUTO)
  var id: Int?,
  var userName: String?, // User name 
  var age: Int?, // Age 
  var password: String?, // Password 
  var name: String?, // Name 
  var email: String?  // Mailbox 
) : Serializable

2.3 Non-parametric notes in kotlin-jpa

If you have already added the kotlin-jpa plug-in to your project, you basically don't have to add a separate non-parametric plug-in. kotlin-jpa wraps the non-parametric plug-in and supports it by default when you use @ Entity, @ Embeddable, and @ MappedSuperclass annotations.

3. Reference articles

Kotlin Official Documents


Related articles: