Using multiple annotations in Kotlin can become quite ugly. The take up more lines than the meaning they convey is worth, and some annotations are often used together.
Take this small Jetpack Compose function for example:
@Preview
@Composable
fun Preview_ConfigurationList() = AppTheme {
ConfigurationList()
}
The @Preview
and @Composable
annotations are both necessary and need to be used in conjunction. You could of course just write them both on the same line.
But how could you convey their special bond, save a line of code, and be extra fancy?
By using a barely documented feature of Kotlin!
The Annotation Array
Pinterest’s ktlint rule on annotation formatting is the only source where I ever saw this language feature, writing multiple annotations in an array like this:
@[Preview Composable]
fun Preview_ConfigurationList() = AppTheme {
ConfigurationList()
}
Even the Kotlin docs do not mention this, at least not here, where I expected it…
Limitations
If you intend to use this with ktlint, be aware that you should not use it for annotations with parameters (but it is possible). You could disable the rule in you .editorconfig
:
ktlint_standard_annotation = disabled
I don’t think the Kotlin devs are likely to take this little thing out, but you never know.