问题描述
使用语言批注,IntelliJ可以被告知将参数视为给定语言,以便启用自动补全和其他IDE工具.
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.
我尝试过:
fun @Language("SQL") String.trimSQL() = this.trimMargin()
但这会导致错误:
Error:(57, 5) Kotlin: This annotation is not applicable to target 'type usage'
推荐答案
当前无法执行此操作.如果在String
类型上创建扩展名,则扩展名将在创建扩展名的作用域中的所有String
上可用,并且无法考虑注释.
There is currently no way to do this. If you create an extension on the String
type, it will be available on all String
s in the scope you've created the extension in, and there is no way to take annotations into account.
Typealiases也基本上被忽略,因此即使您要为String
引入SQLString
typealias,并在其上创建扩展名,该扩展名也可用于任何String
实例.
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.
@yole在下面的评论中有一个要点,我可能误解了这个问题.如果您想为函数调用的接收者添加注释,以便IntelliJ可以像使用以下方法那样对它进行提取:
@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()
...,则您必须使用带有注释的use-site目标,以便将其应用于接收者(即应用于生成的静态方法的第一个参数).
... 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()
这确实在第一个参数上添加了适当的注释-查看字节码(以及从此处进行反编译的Java),除了参数名称外,它们的签名都相同:
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)
但是,对于扩展功能,IntelliJ目前似乎无法接受.也许值得在科特琳问题跟踪器上提交有关此问题的信息.
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.
这篇关于将语言注释放在扩展方法接收器上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!