CodeBlanks Logo Icon CodeBlanks

no-arg

Learn the no-arg compiler plugin.

The no-arg plugin

The no-arg plugin adds a synthetic no-argument constructor for classes with certain annotations. This is needed by frameworks like JPA.

JPA's EntityManager needs a no-arg constructor when it reflectively instantiates entity classes. In Kotlin if you write a class with all parameters, no such constructor exists. The no-arg plugin marks annotations like @Entity; at compile time it adds an invisible no-arg constructor to those classes. The source code stays unchanged, but the bytecode gets the constructor. This lets Hibernate and EclipseLink work smoothly.

A no-arg example

In this lesson we show by hand the constructor that the no-arg plugin adds. Normally the plugin writes it into the bytecode; the source does not show it.

Example: class Entity { val id: Int = 0; constructor() }. Here id defaults to 0; the no-arg constructor uses that. An Entity() call returns an instance whose id is 0. JPA uses this constructor to create the entity, then fills id from the database. This structure is standard in Kotlin + JPA projects.

Practice Write Entity no-arg

Define class Entity. Give it val id: Int = 0 and a constructor() declaration. In main, build val e = Entity() and write println(e.id).

Starter code

Main.kt
// add the Entity class (with id property and constructor)

fun main() {
    // create an Entity and print its id
}

Sample solution

Main.kt
class Entity {
    val id: Int = 0
    constructor()
}
fun main() {
    val e = Entity()
    println(e.id)
}

Expected output

0

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 When is the no-arg plugin needed?

  • When JPA-like frameworks want to build an entity with no args Correct answer
  • To write async methods
  • To add an annotation to a class
  • To launch coroutines

Explanation: JPA builds entities reflectively with no args; no-arg provides that.

2 Complete the constructor declaration

Question
class Entity {
    val id: Int = 0
    ____()
}
Answer
class Entity {
    val id: Int = 0
    constructor()
}

Explanation: constructor() declares a no-arg constructor.

3 Match no-arg parts

Term Meaning
constructor() No-arg constructor
@Entity JPA annotation
val id = 0 Default value
EntityManager JPA manager

All lessons in Expert