If we have a class:
class Customer(val customerName: String) { }
Its contructor parameter customerName
is accessible through getCustomerName()
(because it's also a property). If we want to restrict access to this property we should declare it as private
.
Since in many cases from Java world (and if a class is not intended to be data class) fields which are assigned from constructor parameters are for private / protected use it feels like an additional effort to explicitely declare them private
in Kotlin.
Also, Kotlin classes are final by default, so why not follow this principle for properties? Am I missing something?
Classes, objects, interfaces, constructors, and functions, as well as properties and their setters, can have visibility modifiers. Getters always have the same visibility as their properties. There are four visibility modifiers in Kotlin: private , protected , internal , and public . The default visibility is public .
internal is an alternative to Java's package-private. internal means that the declarations are visible inside a module. internal provides real encapsulation for the implementation details, while in Java's package-private encapsulation could be broken.
Internal is a new modifier available in Kotlin that's not there in Java. Setting a declaration as internal means that it'll be available in the same module only. By module in Kotlin, we mean a group of files that are compiled together.
In our experience explicit public breaks the flow of many DSLs and very often — of primary constructors. So we decided to use it by default to keep our code clean.
In our experience, and from some empirical studies of existing codebases, internal
/public
visibility is best for properties.
Also, Kotlin classes are final by default, so why not follow this principle for properties? Am I missing something?
Properties are final
by default, i.e. they can not be overridden unless you supply the open
modifier explicitly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With