One Off the Slack: Why is @Composable an Annotation?
Altynbek Nurtaza asked a question that comes up from time to time:
Hi everyone! in the videos people say composable functions are very similar to suspend functions. why is Composable a annotation rather than a kotlin keyword?
…[one] possible reason is that they didn’t reserve it: if a developer has a variable called “composable” in their code, they will potentially need to rewrite lot’s of code
Google’s Adam Powell pointed out that this is not the reason:
nah, to use another analogy with suspend, you can name variables
suspend
in your code too and there’s no issue. Kotlin has a lot of “soft keywords” like this that are only keywords in particular contexts, not at a super low level of lexical analysis.
You can read more about Kotlin’s soft keywords in the Kotlin docs.
Instead, the reason is what Albert Chang offered:
I believe it’s because adding a keyword is a huge language design change and can’t be done by a compiler plugin.
That led to a clarification from JetBrains’ Roman Elizarov (formerly Chief Coroutines Cook, and now King of All Kotlin):
It might be a great idea to have this kind of keyword in the language in the future, but it will take a huge amount of work. And this work is not about adding support for a new context-sensitive keyword (that’s trivial). It is the work of unbundling and abstracting of language support from the runtime library (just like it was done for coroutines).
In the end, the only(?) true language change for coroutines was introducing suspend
as a keyword — most of the rest was handled by a library. That is extraordinarily
tricky to pull off and probably only came about because coroutines were being developed
by the same firm that maintains the language itself. Turning @Composable
into composable
would be another leap: allowing arbitrary third parties (e.g., Google) to define new
soft keywords (composable
) as part of a Kotlin compiler plugin. It sounds like this actually
is being considered, but it remains to be seen if Google would migrate Compose to it if this
capability is offered in the future.
Read the original thread in the kotlinlang Slack workspace. Not a member? Join that Slack workspace here!