可见修改
类、对象、接口、构造函数、函数、属性及其setter具有可见性修饰符。(getter总是有相同的可见性属性。)在Kotlin有四个可见性修饰符:
private —
可见只有在声明的范围及其方法(在同一模块);,跟java一 直只有在当前类中可见protected —
(只适用于类/接口成员)像private
,但子类可见;internal —
(默认情况下使用)可见在同一个模块中(如果声明范围是可见的)的所有者,就是在同一个包名下可见;public —
全局可见
note:函数表达式的休和所有属性声明
public
必须显式地指定返回类型这是必需的,所以我们不意外改变一种这是一个公共API的一部分,仅通过改变实现
public val foo: Int = 5 // explicit return type required
public fun bar(): Int = 5 // explicit return type required
public fun bar() {} // block body: return type is Unit and can't be changed accidentally, so not required
请查看以下的解释这些不同类型的声明范围。
包
函数、属性和类对象和接口可以定义“顶级”,即直接在一个包:
// file name: example.kt
package foo
fun baz() {}
class Bar {}
- 如果你不指定任何可见性修饰符,
internal
的是默认情况下,这意味着你的声明将在同一个模块中随处可见 - 如果你标记一个声明
private
的,只有这个包内可见及其子,只有在同一个模块中; - 如果你标记,
public
它到处可见; protected
并不是用于顶级声明
例如:
// file name: example.kt
package foo
private fun foo() {} // visible inside this package and subpackaged
public var bar: Int = 5 // property is visible everywhere
private set // setter is visible only in this package and subpackages
internal val baz = 6 // visible inside the same module, the modifier can be omitted
类和接口
当我们在定义在一个类上时:
private
的意思是可见在这个类中仅(包括其所有成员);protected
— 和private一样再加上子类internal
-所有的client在这个模块下,并且定义的类的成员为internal
可见public
任何的client都可以查看类中public成员
note:在kotlin中内部类不能访问外部类的私有成员
open class Outer {
private val a = 1
protected val b = 2
val c = 3 // internal by default
public val d: Int = 4 // return type required
protected class Nested {
public val e: Int = 5
}
}
class Subclass : Outer() {
// a is not visible
// b, c and d are visible
// Nested and e are visible
}
class Unrelated(o: Outer) {
// o.a, o.b are not visible
// o.c and o.d are visible (same module)
// Outer.Nested is not visible, and Nested::e is not visible either
}
构造函数
class C private constructor(a: Int) { ... }