当然,它们并不是真的重复,我只是不知道如何简短地描述这个概念。它与属性 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 }
关于 "duplicate"属性名称的 kotlin 命名约定?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56913092/