What is the difference between a Property and Open Property in Kotlin? The code below complains on me declaring the setter private and Intellij says private setters are not allowed for open properties. What is an open property?

@RestController
open class ParameterController {

  @Autowired
  lateinit var parameterRepository: ParameterRepository
    private set //error


}

为什么上面的代码无效,而这个代码无效?

open class ItemPrice{

    lateinit var type: String
        private set // ok

}

EDIT: I am using the spring-allopen plugin, and marking the class explicitly as open doesn't make a difference.

推荐答案

What is an open property?

A open property that means its getter/setter(?) is not final. On the other hand, its getter & setter can be override by its subclasses.

In kotlin, everything is declared with final keyword except interface, annotation class, sealed class, enum class, variables, mutable property backing field and parameters, but the immutable variables & parameters are effectivily-final.

Due to the allopen plugin will makes all of the properties & methods opened in the spring components.

However, a open property can't to makes a private setter, if the property is opened, for example:

//v--- allopen plugin will remove all `final` keyword, it is equivalent to `open`
open var value: String=""; private set
//                         ^--- ERROR:private set are not allowed

因此,必须明确地将属性设置为final,例如:

//v--- makes it final explicitly by `final` keyword
final var value: String =""; private set

Kotlin相关问答推荐

当我通过媒体通知更改音乐时不要更新我的 UI

如何在 Kotlin 中为变量分配另一个变量的值?

TestContainers PostgreSQLContainer 与 Kotlin 单元测试:Not enough information to infer type variable SELF

如何为你的 Flutter 元素添加 Kotlin 支持?

jetpack compose 将参数传递给 viewModel

如何解决此错误请Kotlin:[Internal Error] java.lang.ExceptionInInitializerError

Firebase 权限被拒绝

如何在 Android Studio 3.1.3 中查看 Kotlin 中有趣的源代码?

更新到版本4.10.1/4.10.2后 Gradle 同步失败

kotlin RecyclerView分页

将ExpectedException与Kotlin一起使用

Android插件2.2.0-alpha1无法使用Kotlin编译

如何在 Jetpack Compose 的 LazyColumn/LazyRow 中禁用和启用滚动?

TypeConverter()在Android的TypeConverter错误中具有私有访问权限

Gradle:无法连接到 Windows 上的 Kotlin 守护程序

保存对象时未填充 Spring Boot JPA@CreatedDate @LastModifiedDate

在android java类中使用Kotlin扩展

旋转 kotlin 数组

你如何在 Kotlin 中注释 Pair 参数?

在 Kotlin 中声明 Byte 会出现编译时错误The integer literal does not conform to the expected type Byte