Hello guys, i need to know why i need to create cu...
# getting-started
a
Hello guys, i need to know why i need to create custom annotation in Kotlin? what is the benefit of creating custom annotation? Thank You
c
the benefit is whatever you want it to be… generally you’d have a reason to create one, such as use in a code generator or reflective use at runtime in a framework.
some frameworks allow you to create meta-annotations, to combine multiple annotations/settings together into your custom annotation.
a
Thanks for illustration, i think the one reason is to combine more annotations under custom one but is there any use in the real life?
another example that the combination
c
Many places in Spring / Spring Boot use meta-annotations and allow you to create your own. e.g. https://www.logicbig.com/tutorials/spring-framework/spring-web-mvc/meta-annotation.html
👍 1
j
@Abdullah Samir lots of DI frameworks use annotations to find the classes you want them to handle. Another example is serialization libraries, which define annotations to allow you to specify extra information that cannot be expressed in the code itself directly. Any annotation you use is an annotation someone has created, so if you find them useful to use, it means it is useful that someone created it
👍 1
g
There are also 2 more examples that come from Kotlin stdlib: 1. Kotlin provides ability for creating your own DSLs. To make the DSL work consistently there are means to prevent some initial bad behaviour by declaring your own DSL marker and using it for your DSL. For example, HtmlTagMarker in kotlinx.html. 2. There are cases when you have to show users of your library (code) that there are some issues in working with particular entities. Like in case when you deprecate something or in case when something is very delicate and should be used with caution. Then opt-in requirements can help you. To use them you need to declare your own annotation and mark all the particular entities with it. For example, DelicateCoroutineApi in kotlinx.coroutines.