Putting language annotations on extension method r

2019-08-09 21:05发布

问题:

Using the Language annotation, IntelliJ can be told to treat parameters as being of a given language, so that autocompletion and other IDE tools can be enabled.

Can this be done for receiver parameters too, or are there other ways to get language features for extended types.

I have tried:

fun @Language("SQL") String.trimSQL() = this.trimMargin()

but this gives the error:

Error:(57, 5) Kotlin: This annotation is not applicable to target 'type usage'

回答1:

There is currently no way to do this. If you create an extension on the String type, it will be available on all Strings in the scope you've created the extension in, and there is no way to take annotations into account.

Typealiases are also basically ignored, so even if you were to introduce an SQLString typealias for String, and create the extension on that, the extension would be available for any String instance.


Edit: @yole had a good point in the comment below, I might have misunderstood the question. If you want to annotate the receiver of the function call so that IntelliJ can pick it up, like it would for a method like this:

fun trimSQL(@Language("SQL") str: String) = str.trimMargin()

... then you'd have to use a use-site target with the annotation so that it's applied to the receiver (i.e. applied to the first parameter of the generated static method).

fun @receiver:Language("SQL") String.trimSQL() = this.trimMargin()

This does put the appropriate annotation on the first parameter - looking at the bytecode (and decompiled Java from there), both of their signatures are the same other than parameter names:

@NotNull
public static final String trimSQL2(@Language("SQL") @NotNull String str)

However, IntelliJ doesn't seem to be able to pick this up at the moment for the case of the extension function. Perhaps it's worth submitting an issue about it on the Kotlin issue tracker.