Reputation: 117
Put differently, what is the difference between Kotlin interfaces and annotations?
I ask this because in the "Docs" I read that annotation classes are a form of interface, and to me, I cannot tell the main difference between the two. The link to the docs: https://kotlinlang.org/docs/annotations.html#instantiation
I have avoided asking this question but surprisingly, I could not find a clear answer to this question online.
Any help would be appreciated.
Upvotes: 3
Views: 784
Reputation: 93591
No point about explaining what interfaces are here because there are thousands of articles about them because they are a basic feature in almost every OOP.
Annotations are technically a subtype of interfaces, but that’s not really helpful to understanding them because you don’t use them in typical code for purposes anything like interfaces.
Annotations are for attaching meta data to code, which can be used to enable features not directly supported by the language syntax.
In Kotlin, a number of them are provided for enabling JVM features that aren’t relevant to other platforms so they weren’t included in the language syntax. For example, @Synchronized
and @JvmField
. There’s also one for future-proofing inline classes on the JVM, @JvmInline
, which is there to distinguish the compiled Kotlin-specific version of inline classes from the future default implementation that will be equivalent to Java record
s.
On Android some are provided to enable compiler warnings and errors for issues specific to Android code, such as using the wrong type of resource ID as a function argument, e.g. @ColorRes
or @StringRes
. They also provide ones that can be used by the build tools after compilation, such as @Keep
, which prevents a class from being minified and obfuscated in a release build.
Some libraries that use reflection provide annotations that help the library know what to do with code. For example, Gson, which is used for automatically converting classes to and from JSON Strings, has ones for specifying what name a field should be converted to in the String, for example.
Making your own is a somewhat advanced skill. It would be more common to do something like the ones used by GSON, if you building your own tool that uses reflection. But you could also use it for compiler tools and linters like the above Android examples.
Upvotes: 6