Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is `open` keyword for fields in Kotlin? [duplicate]

Tags:

java

kotlin

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 overridden
val property is final field in java

what about open property?

like image 213
M.T Avatar asked Mar 02 '18 19:03

M.T


People also ask

What does the open keyword do in Kotlin?

It means 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. Note: your class is implicitly declared as open since it is abstract, hence you cannot create an instance of that class directly.

What is open modifier in Kotlin?

open modifier marks classes and methods as overridable. You need one per each method you want to be overridable. Now Button is marked as open, so it can be inherited. click() must be explicitly marked as open to be overridable.

What is difference between open and public in Kotlin?

The open keyword symbolizes open for extension. With the open keyword, any other class can inherit from this class. On the other hand, the public keyword is an access modifier. It is the default access modifier in Kotlin.

What does ?: Mean in Kotlin?

In certain computer programming languages, the Elvis operator ?: is a binary operator that returns its first operand if that operand is true , and otherwise evaluates and returns its second operand.


1 Answers

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.

like image 104
user2340612 Avatar answered Oct 01 '22 09:10

user2340612