简体   繁体   English

为方法或类抑制“使用属性访问语法”

[英]Suppress “Use property access syntax” for method or class

In my project, I have a delegate(written in Java) for fetching data by RPC, most of it methods start with 'get' and some require no parameters, so Kotlin suggests to replace calls to them with property access syntax while they are not fulfilling property semantics (well, because they perform network requests), so I'd like to suppress all such inspections for all these methods usages by default and not in place of every call (yes, I'm aware of @Suppress annotation for blocks, and it works exactly opposite to what I need). 在我的项目中,我有一个委托(用Java编写)用于通过RPC获取数据,大多数方法以'get'开头,有些不需要参数,因此Kotlin建议用属性访问语法替换对它们的调用,而不是实现属性语义(好吧,因为它们执行网络请求),所以我想默认禁止所有这些方法使用所有这些检查,而不是代替每个调用(是的,我知道块的@Suppress注释) ,它与我需要的完全相反)。

Is there any solution for this except renaming them so they won't start with 'get'? 有没有任何解决方案除了重命名,所以他们不会以'get'开头?

I suppose that you use IntelliJ IDEA. 我想你使用IntelliJ IDEA。

You can go to Preferences, Editor, Inspection, Kotlin, Accessor call that can... and uncheck it. 您可以转到Preferences, Editor, Inspection, Kotlin, Accessor call that can...并取消选中它。 (Or type property syntax in search filter). (或在搜索过滤器中键入property syntax )。

This will disable this warning on your whole project. 这将在整个项目中禁用此警告。 You may also change the severity to something else that suit your needs. 您也可以将严重性更改为适合您需要的其他内容。

EDIT : You can use the @Suppress annotation. 编辑 :您可以使用@Suppress注释。

Suppose you have a Java class named A exposing methods: 假设您有一个名为A公开方法的Java类:

  • getA() this one is a regular Java bean access, getA()这个是一个常规的Java bean访问,
  • getB() this one is a network call for example. getB()这个是网络调用。

You can write: 你可以写:

fun main(args: Array<String>) {
    val a = A()
    println(a.a)
    @Suppress("UsePropertyAccessSyntax")
    print(a.getB())
}

@Suppress can be used at several levels. @Suppress可用于多个级别。 See Documentation . 文档

IntelliJ IDEA has a nice help to suppress those warnings. IntelliJ IDEA有很好的帮助来抑制这些警告。 想法屏幕截图

EDIT2 : 编辑2
Disclaimer : There is an other way to do that, but I will not use it myself as it is ugly and I prefer having a warning than using it. 免责声明:有另一种方法可以做到这一点,但我不会自己使用它,因为它很难看,我更喜欢发出警告而不是使用它。

You can use Kotlin extensions and rename your network getters like this. 您可以使用Kotlin扩展并重命名您的网络getter。

The Java class: Java类:

public class A {
    private int a;

    int getA() {
        return a;
    }

    A _getB() {   // Was getB()
        return this;
    }
}

The Kotlin file: Kotlin文件:

fun A.getB() : A {       // Kotlin extension
    return this._getB()
}

fun main(args: Array<String>) {
    val a = A()
    println(a.a)
    print(a.getB()) // No warning here
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM