"duplicate"属性名称的 kotlin 命名约定?

标签 kotlin coding-style

当然,它们并不是真的重复,我只是不知道如何简短地描述这个概念。它与属性 getter 有关,这些属性 getter 仅用于公开另一个访问权限被隐藏的属性的转换。这里我用一段代码来解释一下:

class MyClass {
    internal val _children = mutableListOf<MyClass>()
    val children: List<MyClass> get() { return _children.toList() }
}

Children 可以在内部修改,也应该暴露给外界,但他们不应该能够修改列表。我认为这是一个相当可以理解的情况。

我直观地选择了在 Angular( typescript )和 C# 中遇到的 _name 约定,这似乎在类似情况下很常见。 但 intellij 提示说,按照惯例,所有属性名称都应以小写字母开头。

Kotlin 中是否有针对此类事物的另一种命名约定,或者 IDE 根本看不到我正在尝试执行的操作(这并不奇怪),而我应该忽略它?

最佳答案

是的,编码约定建议 在私有(private)支持属性名称前面添加下划线,就像您对 _children 所做的那样:

Names for backing properties

If a class has two properties which are conceptually the same but one is part of a public API and another is an implementation detail, use an underscore as the prefix for the name of the private property:

class C {
    private val _elementList = mutableListOf<Element>()

    val elementList: List<Element>
         get() = _elementList
}

参见Property names

关于 "duplicate"属性名称的 kotlin 命名约定?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56913092/

相关文章:

kotlin - 测试代码时为什么会出现错误 “Unresolved reference: launch”?

android - 无法在写入事务之外修改托管对象(Realm + Android)

c - 为什么使用这个结构?疯子还是天才?

java - Sun (1999) 的 "Code Conventions for the Java Programming Language"是否过时?

coding-style - protobuf 的最佳文件命名风格是什么?

java - 抛出异常或者返回错误信息

kotlin - 我是否需要在@Composable 中使用 repeatOnLifecycle 扭曲热流的 collectAsState()?

spring - @CreationTimestamp 和 @UpdateTimestamp 在 Kotlin 中不起作用

kotlin - 在 Kotlin 函数中传递值时遇到问题。正在转换的变量 :(String)->R

Java 编码标准 : variable declaration