what is `open` keyword for fields in Kotlin? [duplicate]
In Kotlin open
is the same as not final
in Java for classes and methods.
What does open
give me in the following class for the field marked as open
?
@MappedSuperclass
abstract class BaseEntity() : Persistable<Long> {
open var id: Long? = null
}
updated this is not duplicate of What is the difference between 'open' and 'public' in Kotlin?
I am interested in open
keyword for properties
updated
open
class can be inherited.open
fun can be overriddenval
property is final
field in java
what about open
property?
As you said, the open
keyword allows you to override classes, when used in the class declaration. Accordingly, declaring a property as open
, allows subclasses to override the property itself (e.g., redefine getter/setter). That keyword is required since in Kotlin everything is "final
" by default, meaning that you can't override
it (something similar to C#, if you have experience with that).
Note that your class is implicitly declared as open
since it is abstract
, hence you cannot create an instance of that class directly.
final method in Java: A method that cannot be overridden.
final class in Java: A class that cannot be extended.
Open classes and methods in Kotlin are equivalent to the opposite of final in Java, an open method is overridable and an open class is extendable in Kotlin.