CodeBlanks Logo Icon CodeBlanks

Summary - Compiler plugins

Combine IR, all-open and no-arg to write a framework integration.

Summary - Compiler plugin

In this group you learned compiler plugin, IR, plugin vs KSP, all-open and no-arg. Now you will write a model that combines them: an open Entity and its subclass.

Your Entity will be open; its tag() method will also be open. A User subclass will override tag(). In main you will do a polymorphic assignment and print the result. This is a typical entity scenario where all-open and no-arg meet.

Combining: open Entity

Now we will do by hand what all-open does: mark Entity and tag() as open. Then add a subclass.

Example: open class Entity(val id: Int) { open fun tag(): String = "Entity" }. class User(id: Int) : Entity(id) { override fun tag(): String = "User" }. The assignment val e: Entity = User(7); the call e.tag() returns "User". This is polymorphic behaviour. The all-open plugin does this automatically; we model it. This structure is the basis of framework proxies.

Practice Write Open Entity + User

Define open class Entity(val id: Int) with open fun tag(): String = "Entity". Define class User(id: Int) : Entity(id) with override fun tag(): String = "User". In main, write val e: Entity = User(7) and println("${'$'}{e.tag()}:${'$'}{e.id}").

Starter code

Main.kt
// add the Entity and User classes

fun main() {
    // print the polymorphic call
}

Sample solution

Main.kt
open class Entity(val id: Int) {
    open fun tag(): String = "Entity"
}
class User(id: Int) : Entity(id) {
    override fun tag(): String = "User"
}
fun main() {
    val e: Entity = User(7)
    println("${e.tag()}:${e.id}")
}

Expected output

User:7

Questions and answers

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

1 Which action can only be done by a plugin?

  • Read annotations
  • Make a class open Correct answer
  • Return a list
  • Generate a new file

Explanation: Making a class open modifies existing code; only a plugin can do it.

2 Complete the tag method

Question
open class Entity(val id: Int) {
    open fun ____(): String = "Entity"
}
Answer
open class Entity(val id: Int) {
    open fun tag(): String = "Entity"
}

Explanation: tag() returns the entity type.

3 Match plugin concepts

Term Meaning
all-open Makes a class open
no-arg Adds a synthetic constructor
IR Intermediate representation
compose Transforms Composables

All lessons in Expert