Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is an open property? Why I can't make its setter to private?

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.

like image 652
greyfox Avatar asked Jul 17 '17 21:07

greyfox


1 Answers

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
like image 132
holi-java Avatar answered Sep 22 '22 17:09

holi-java