Kotlin Reference (十一) Visibility Modifiers
来源:互联网 发布:身份证登记软件下载 编辑:程序博客网 时间:2024/05/17 12:56
most from reference
类,对象,接口,构造函数,函数,属性及setters具有可见性修饰符(getter总是具有和属性一样的可见性)。在kotlin中油4个可视化修饰符:private,protected,internal,public。如果没有显式修饰符,则使用默认可见性public。
包
函数,属性和类,对象和接口可以在顶级上声明,即直接在包中:
// file name: example.ktpackage foofun baz() {}class Bar {}
- 如果不指定任何可见性修饰符,默认使用public,这意味着您的声明将在任何地方都可见;
- 如果标记privatge, 它只会在包含该声明的文件内部可见;
- 如果标记internal,它在同一个模块中到处可见;
- protected不适用与顶级声明。
例子:
// file name: example.ktpackage fooprivate fun foo() {} // visible inside example.ktpublic var bar: Int = 5 // property is visible everywhere private set // setter is visible only in example.ktinternal val baz = 6 // visible inside the same module
类和接口
对于在类中声明的成员:
- private 意味着在这个类内可见(包括其所有成员);
- protected 与private子类中的可见一样;
- internal 该模块中看到声明类的任何客户端都看到其internal成员;
- public 任何看到声明类的客户看到其public成员。
注意 Java用户:外部类不会在Kotlin中看到其内部类的私有成员。
如果您覆盖protected成员并且不明确指定可见性,则覆盖成员也将具有protected可见性。
例子:
open class Outer { private val a = 1 protected open val b = 2 internal val c = 3 val d = 4 // public by default 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 override val b = 5 // 'b' is protected}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) { ... }
这里的构造函数是私有的。默认情况下,所有的构造函数都是public有效,相当于他们在类可见的地方可见(即internal类的构造函数只能在同一模块中可见)。
本地声明
局部变量,函数和类不能有可见性修饰符。
模块
internal可见性意味着该部件是用相同的模块可见的。更具体地说,一个模块是一组编译的Kotlin文件:
IntelliJ IDEA模块;
- 一个Maven项目;
- 一个Gradle源集;
- 一组文件用一次调用编译 蚂蚁任务。
阅读全文
0 0
- Kotlin Reference (十一) Visibility Modifiers
- Kotlin-11.可见性修饰符(Visibility Modifiers)
- Kotlin Reference (十一) 泛型、数组型变、泛型型变、泛型约束
- Kotlin Reference (六) 接口
- kotlin Unresolved reference: kotlinx
- Kotlin Reference (二) Idioms
- Kotlin Reference (五) Packages
- Kotlin Reference (十) Interfaces
- Kotlin Reference (十二) Extensions
- Kotlin Reference (十四) Generics
- Kotlin Reference (一) Basic Syntax
- Kotlin Reference (四) control flow
- Kotlin Reference (七) feature: Range
- Kotlin Reference (一) Basic Syntax
- Kotlin Reference (三) Coding Conventions
- Kotlin Reference (四) Basic Types
- Kotlin Reference (六) Control Flow
- Kotlin Reference(一)-入门指南
- 设计模式六大原则之迪米特法则
- 解决Missing artifact com.microsoft.sqlserver:sqljdbc4:jar:4.0问题
- poi操作中Invalid char (*) found at index (22) in sheet name
- C++预科——C语言指针回顾(四) 指针与数组之间的关系
- 解析Csv文件并转化为DataTable(处理支付宝当面付账单)
- Kotlin Reference (十一) Visibility Modifiers
- ethercat状态机
- java 备份(转存)数据库到云服务器或本地磁盘
- Swift Router 页面跳转路由,组件解耦
- 小程序怎么打断点
- Android 7.0 去电流程
- 代码干货 | H5和NA(WebView)的交互
- 敌兵布阵
- 部门递归处理