11

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?

2 Answers 2

9

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.

Sign up to request clarification or add additional context in comments.

Comments

0

A Protected Modifier in Kotlin: CANNOT be set on top-level declarations. Declarations that are protected in a class, can be accessed only in their subclasses.

for more details you can use this link

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.