WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Kotlin · Intermediate · question 33 of 100

How can you create and use an annotation in Kotlin? Provide an example.?

📕 Buy this interview preparation book: 100 Kotlin questions & answers — PDF + EPUB for $5

Annotations in Kotlin are a way of adding metadata to our code. They can be used to provide additional information to the compiler, to generate code at compile time, or to be processed by third-party tools. In Kotlin, we can create our own annotations using the ‘@interface‘ keyword. Let’s see an example:

@Target(AnnotationTarget.CLASS)
@Retention(AnnotationRetention.RUNTIME)
@MustBeDocumented
annotation class Entity(val tableName: String)

Let’s explain the above code:

- We use the ‘@interface‘ keyword to define the annotation class ‘Entity‘.

- The ‘@Target‘ annotation specifies where this annotation can be used. In this case, we have defined that this annotation can only be applied to classes using the ‘AnnotationTarget.CLASS‘.

- The ‘@Retention‘ annotation specifies how the annotation is stored. In this case, we have set ‘AnnotationRetention.RUNTIME‘, which means that the annotation can be accessed at runtime (useful for reflection).

- The ‘@MustBeDocumented‘ annotation indicates that this annotation should be included in the generated documentation.

The ‘Entity‘ annotation has a parameter ‘tableName‘ that takes a string value. We can use this annotation as follows:

@Entity(tableName = "users")
class User(val id: Int, val name: String)

This code applies the ‘@Entity‘ annotation to the ‘User‘ class and sets the ‘tableName‘ parameter to ‘"users"`. We can now access this information at runtime using reflection:

val user = User(1, "John")
val entityAnnotation = user.javaClass.getAnnotation(Entity::class.java)
println("Table name: ${entityAnnotation?.tableName}")

This would output ‘Table name: users‘, which is the value we set in the ‘@Entity‘ annotation.

In summary, annotations are an important tool in Kotlin that allow us to add metadata to our code. We can create our own annotations using the ‘@interface‘ keyword and apply them to classes, functions, or properties using their respective ‘@Target‘ annotations. We can access this metadata at runtime using reflection, which allows us to dynamically generate code or process our code in different ways.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Kotlin interview — then scores it.
📞 Practice Kotlin — free 15 min
📕 Buy this interview preparation book: 100 Kotlin questions & answers — PDF + EPUB for $5

All 100 Kotlin questions · All topics