Kotlin Visibility Modifiers
Visibility modifiers determine the scope in which a class, function, or property can be accessed.
Kotlin provides four modifiers: public, internal, protected, and private.
Using them wisely can hide implementation details and prevent external code from depending on things it should not.
Overview of the four modifiers
The modifiers available depend on the location; the table below gives an overall picture.
| Modifiers | Top-level declarations | Class member | Visibility scope |
|---|---|---|---|
| public | Available (default) | Available (default) | Anywhere |
| internal | Available | Available | Within the same module |
| protected | Unusable | Available | Inside this class and its subclasses |
| private | Available | Available | Top-level declaration: this file; class member: this class |
Kotlin has no "package-level visibility" like Java.
Without a modifier, a declaration is public; the package name does not affect visibility.
Note:protected cannot be used on top-level declarations, only on members of classes or interfaces.
private: same file at top level, only this class within a class
The meaning of private depends on whether it modifies a top-level declaration or a class member, and the two are easy to confuse.
When modifying a top-level declaration, private means visible only within this source file; other files cannot access it even if they share the same package name.
Example
// File: RunoobFile.kt
private
const
val SITE
:
String
=
"www.runoob.com"
// Top-level private: visible only in this file
fun printSite
(
)
{
println
(
SITE
)
// Accessible within the same file
}
// File: Main.kt (compiled together with RunoobFile.kt)
fun main
(
)
{
printSite
(
)
// Can be called; printSite is public
// println(SITE) // Compile error: Cannot access 'SITE': it is private in file
}
www.runoob.com
When modifying a class member, private means only this class's own interior can access it; not even subclasses can.
Example
class
RunoobAccount
{
private
var balance
:
Double
=
0.0
// Visible only within this class
fun deposit
(
amount
:
Double
)
{
// The interior can freely read and write private properties
require
(
amount
0
)
{
"Amount must be greater than 0"
}
balance
+=
amount
}
fun showBalance
(
)
:
String
=
"Balance: $balance yuan"
}
fun main
(
)
{
val account
=
RunoobAccount
(
)
account.
deposit
(
100.0
)
println
(
account.
showBalance
(
)
)
// println(account.balance) // Compile error: balance is private
}
余额:100.0 元
private members likewise cannot be accessed directly by subclasses.
If you want subclasses to use it, use protected instead, or provide a public method to expose it indirectly.
protected: visible only inside subclasses
protected is the easiest of the four modifiers to get wrong.
Kotlin's protected is visible only inside this class and its subclasses; outside that scope, it cannot be accessed even from the same file or same package.
This differs from Java: Java's protected also allows same-package access, while Kotlin does not.
Example
open
class
RunoobAnimal
{
protected
var name
:
String
=
"Runoob Cat"
// Visible inside the subclass
protected
fun showName
(
)
:
String
=
"Animal name: $name"
}
class
RunoobCat
:
RunoobAnimal
(
)
{
fun introduce
(
)
{
name
=
"Runoob Kitten"
// A subclass can access protected properties internally
println
(
showName
(
)
)
// A subclass can call protected methods internally
}
}
fun main
(
)
{
val cat
=
RunoobCat
(
)
cat.
introduce
(
)
// println(cat.name) // Compile error: protected member is not visible outside the class
// cat.showName() // Compile error: same as above
}
动物名称:Runoob 小猫
protected also cannot be used on top-level declarations; the following cannot compile.
Example
// Compile error: Modifier 'protected' is not applicable to top-level declarations
// protected fun runoobHelp(): String = "Help Center"
// Correct form: top level should be either public or private / internal
fun runoobHelp
(
)
:
String
=
"Help Center"
fun main
(
)
{
println
(
runoobHelp
(
)
)
}
帮助中心
Note:Kotlin's protected does not mean "visible in the same file or in subclasses". Same-file visibility is the semantics of top-level private; protected is visible only inside the class and its subclasses and has nothing to do with packages.
internal: visible within the module
internal means "visible within the same module, invisible outside the module".
It suits implementations that are not intended as public APIs but need to be shared by multiple files in the same project.
Example
// File: Logger.kt
internal fun log
(
message
:
String
)
{
println
(
"[RUNOOB] $message"
)
}
internal
class
RunoobLogger
{
internal val tag
:
String
=
"RUNOOB"
}
// File: Main.kt (in the same module as Logger.kt)
fun main
(
)
{
log
(
"Can be called directly within the module"
)
val logger
=
RunoobLogger
(
)
println
(
logger.
tag
)
}
[RUNOOB] 模块内可以直接调用
RUNOOB
If another module references this project, it cannot access log and RunoobLogger; the compiler will say it is internal in
public: the default visibility
When no modifier is written, a declaration's visibility is public.
public members can be accessed anywhere; the following three forms are completely equivalent.
Example
public
class
RunoobSite
// Write public explicitly
class
RunoobMirror
// Omit the modifier, and it is public by default
public
fun runoobHello
(
)
:
String
=
"Hello RUNOOB"
fun runoobHi
(
)
:
String
=
"Hi www.runoob.com"
public
val siteName
:
String
=
"RUNOOB"
val siteUrl
:
String
=
"www.runoob.com"
fun main
(
)
{
println
(
runoobHello
(
)
)
println
(
runoobHi
(
)
)
println
(
"$siteName - $siteUrl"
)
}
Hello RUNOOB
Hi www.runoob.com
RUNOOB - www.runoob.com
Generally you write public explicitly only when you need to emphasize "this is a public API".
The definition of "module"
The boundary of internal is the "module", so we must first clarify what a module is.
A module is a set of Kotlin source files compiled together; common forms are listed below.
| Forms of a module | Description |
|---|---|
| IntelliJ IDEA module | A project module described by an .iml file |
| Maven Project | A project described by a pom.xml |
| Gradle source set | Source sets such as main and test |
| A single kotlinc invocation | All files compiled together in one command-line invocation |
Gradle additionally passes the output of the main source set to the test source set's compilation as a friend module, so test code can access internal declarations in main.
Conversely, two independent Gradle projects cannot see each other's internal members even if their package names are completely identical.
Constructor visibility
Constructors can also have visibility, controlling who can create an instance of the class.
To give the primary constructor a visibility, you must include the constructor keyword; for secondary constructors, put the modifier directly before constructor.
Example
// Primary constructor set to private: outsiders cannot create instances directly
class
RunoobSingleton
private
constructor
(
)
{
companion object
{
private
val instance
=
RunoobSingleton
(
)
fun getInstance
(
)
:
RunoobSingleton
=
instance
}
}
// Primary constructor set to internal: instances can only be created within the same module
class
RunoobConfig internal constructor
(
val host
:
String
, val port
:
Int
)
fun main
(
)
{
val config
=
RunoobConfig
(
"www.runoob.com"
,
80
)
println
(
"${config.host}:${config.port}"
)
// RunoobSingleton() // Compile error: the primary constructor is private
val single
=
RunoobSingleton.
getInstance
(
)
println
(
single.
javaClass
.
simpleName
)
}
www.runoob.com:80
RunoobSingleton
A property's setter can also have its own visibility; a common pattern is "read-only outside, writable inside".
Example
class
RunoobUser
{
var name
:
String
=
"runoob"
private
set
// setter visible only within this class; outsiders can read but not modify
fun rename
(
newName
:
String
)
{
name
=
newName
// The class itself can still modify it
}
}
fun main
(
)
{
val user
=
RunoobUser
(
)
println
(
user.
name
)
user.
rename
(
"RUNOOB"
)
println
(
user.
name
)
// user.name = "Runoob Tutorial" // Compile error: setter is private
}
runoob
RUNOOB
Visibility rules when overriding
When a subclass overrides a superclass member, visibility can only be widened, never narrowed.
If no modifier is written with override, the overriding member inherits the visibility of the superclass member.
Example
open
class
RunoobBase
{
protected
open fun runoobTip
(
)
:
String
=
"Hint from the base class"
}
class
RunoobChild
:
RunoobBase
(
)
{
// Allowed: widen protected to public
public
override fun runoobTip
(
)
:
String
=
"Hint from the subclass"
}
fun main
(
)
{
println
(
RunoobChild
(
)
.
runoobTip
(
)
)
// Now it is public and can be called from outside the class
}
来自子类的提示
The following narrows the visibility, and the compiler reports an error directly.
Example
open
class
RunoobBase2
{
open fun runoobInfo
(
)
:
String
=
"info"
}
class
RunoobChild2
:
RunoobBase2
(
)
{
// Compile error: 'runoobInfo' has weaker access privileges than the overridden declaration
// private override fun runoobInfo(): String = "info"
}
Common questions
Below are a few pitfalls that beginners often run into.
Which to choose, private or internal
Use private for helper functions used in only one file; use internal for those that must cross files but should not be exposed to external users.
When in doubt, write private first and widen it only when you truly need to; this is the safest approach.
Why Java code cannot call Kotlin's internal methods
On the JVM, the compiler appends the module name as a suffix to internal member names; this process is called name mangling.
So the original name is invisible in Java; this is not a permissions issue but a rewritten name.
Can a public function return an internal type?
No; the compiler reports public function exposes its internal return type.
Because external modules cannot obtain this type, it amounts to providing an unusable API.
Can local variables have visibility modifiers?
No; local variables, function parameters, and local functions cannot have visibility modifiers.
Their visibility is already confined to the scope in which they are declared.