13

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


}

Why is the code above not valid but this code is?

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.

holi-java
  • 29,655
  • 7
  • 72
  • 83
greyfox
  • 6,426
  • 23
  • 68
  • 114
  • Your code has too much noise. Try to create a [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve). – nhaarman Jul 17 '17 at 21:39

1 Answers1

18

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

So you must make the property as final explicitly, for example:

//v--- makes it final explicitly by `final` keyword
final var value: String =""; private set
Community
  • 1
  • 1
holi-java
  • 29,655
  • 7
  • 72
  • 83
  • I am using the Spring-openall plugin, I'll edit my question to reflect that – greyfox Jul 17 '17 at 21:43
  • Confirmed this is the correct answer. If I remove the Spring annotations the error does go away. The variables are now being declared as lateinit final var repo: ParameterRepository private set – greyfox Jul 18 '17 at 03:00