Visibility modifiers

Visibility modifiers define how your declarations are accessible from other classes and packages. In Kotlin you can use the same modifiers that are found in Java, private, protected, and public.

Private visibility modifiers restrict access to the same class or a file. And public opens the access to everybody, no matter where they are trying to access a member from.

Java also has a fourth visibility modifier, package-private, which is also a default visibility modifier (if you don’t specify a visibility modifier, then package-private is implicitly applied). Package-private in Java means that declarations are visible only inside the same package. It is easy to bypass this visibility modifier. In your code, you can declare a package with the same name as the one you wish to import from and thus break the access restriction. This is one of the reasons Kotlin doesn’t have the package-private modifier. Instead, Kotlin has a similar one, internal. Internal restricts visibility to the same modules. Definition of a module varies per build system, but it can be described as a single compilation unit. In Gradle, this would be a Gradle module or a project.

Since internal is not available in Java, it also doesn’t exist in Java bytecode. So the Kotlin compiler is responsible for enforcing its access rules. Internal is compiled to public in Java bytecode, which means that anybody will be allowed to call your internal Kotlin code from Java.

Kotlin, being an object-oriented language, allows you to use visibility modifiers on fields, properties, functions, interfaces, and classes. The default visibility modifier in Kotlin is public.

Another difference from Java is that, in Kotlin, the private modifier declared on a file level is visible to all declarations in that file. As this example shows:

private fun sayMyName(name: String) {
println(name)
}
fun accessPrivateFunc() {
sayMyName("John")
}

The following table summarizes all Kotlin visibility modifiers:

Modifier
Visibility
private
inside the same class or a file
protected
inside subclasses
internal
inside same module
public (default)
everywhere
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.155.216