Where can I learn more about annotations? I'm read...
# getting-started
m
Where can I learn more about annotations? I'm reading through the docs on the Kotlin website but not finding much that's useful to me. Here's what I'm trying to do: I want to annotate functions that belong to a class. Those annotated functions when called should, instead of being executed right away, be added to a BlockingQueue that belongs to the containing class. So far I've figured out that I can make a
annotation class Queueable
with a Target of
AnnotationTarget.FUNCTION
. I'm not finding any documentation anywhere on how I can accomplish the rest of what I'd like to do though... In Python, for example, I can annotate a function and access it's arguments and other properties about it since the annotation wraps the function. Am I thinking about annotations incorrectly in Kotlin?
a
Kotlin use annotations just like Java, that is as a metadata. Thus, there are some things you need to be aware of if you don’t want to resort into creating your own annotation processor: 1. If you need the annotation at runtime, you need to retain the annotation class under
@Retention(RetentionPolicy.RUNTIME)
2. You can then access this via reflection. I attached a simple snippet below in Java. How you do it in Kotlin and finally achieve what you want will be left as an exercise 😄
k
What you do with annotations in Python you'd just do with normal code in Kotlin:
Copy code
class Test {
    val queue = ArrayDeque<() -> Unit>()
    private fun wrap(block: () -> Unit) {
        queue.add(block)
    }

    fun foo(arg: String) = wrap {
        println("foo $arg")
    }
}
Because you seem to be used to Python I'll note that the
=
in
foo
is just an expression body, you don't actually assign
foo
to something.
☝️ 1