Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin: why do constructor parameters have "internal" visibility by default?

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?

like image 749
Alexey Dmitriev Avatar asked Mar 09 '15 14:03

Alexey Dmitriev


People also ask

What is the default visibility modifier of a constructor in Kotlin?

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 .

What is difference between internal and private in Kotlin?

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.

What does internal mean in Kotlin?

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.

Why is Kotlin public by default?

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.


1 Answers

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.

like image 113
Andrey Breslav Avatar answered Sep 28 '22 07:09

Andrey Breslav