Kotlin构造函数
来源:互联网 发布:淘宝电子书阅读器 编辑:程序博客网 时间:2024/06/01 12:28
构造函数
当Kotlin中的类需要构造函数时,可以有一个主构造函数和多个次构造函数,可以没有次构造函数。主构造函数在类名后。
//常规用法class Person(name: String) {}
当主构造函数有注解或者可见性修饰符,需加 constructor 关键字。
class Personpublic public @Inject constructor(name: String){}
1、主构造函数
主构造函数不能包含任何的代码。初始化的代码可以放到以 init 关键字作为前缀的初始化块中:
1、当在主函数中声明后可以当做全局变量使用
注:
1、函数的声明可以是val也可以是var
2、当不在主构造函数中声明又想当全局变量使用,可在类中声明,主函数中声明是简化了其写法。
class Test(name: String){ val name = name //。。。}
2、当不在主函数中声明时,只能在初始化块以及属性声明中使用
2、次构造函数
1、次构造函数不能有声明 val 或 var
2、如果类有一个主构造函数(无论有无参数),每个次构造函数需要直接或间接委托给主构造函数,用this关键字
class Person { constructor() { } constructor(name: String):this() { } constructor(name: String, age: Int) : this(name) { }}
class Customer(){ constructor(name: String):this() { } constructor(name: String, age: Int) : this(name) { }}
3、当没有主构造参数时,创建次构造函数
正确使用:
class Customer{ constructor(name: String) { } constructor(name: String, age: Int) : this(name) { }}
错误使用:
class Customer{ //没有主构造函数,使用委托this()错误 constructor(name: String) : this() { } constructor(name: String, age: Int) : this(name) { }}
3、构造函数的使用
两种构造函数结果相同,调用时都可直接调用,或传递一个参数或两个参数进行调用
class Test{ init{ test() test2() } fun test(){ Person() Person("李四") Person("李四",18) } fun test2(){ Customer() Customer("李四") Customer("李四",18) }}
0 0
- Kotlin构造函数
- Kotlin构造函数
- Kotlin中的构造函数
- Kotlin之构造函数
- kotlin 构造
- kotlin的 类,继承,重载,抽象类,构造函数
- Android中Kotlin语言构造函数的使用
- Kotlin学习记录(二)—— Kotlin的变量、属性、类、构造函数、继承、方法
- Kotlin 函数
- Kotlin-函数
- Kotlin -- 函数
- Kotlin-函数
- Kotlin函数
- kotlin 构造方法
- Kotlin构造方法
- Kotlin Reference (五) 类的构造函数,类的继承,属性操作
- 分享下学习Kotlin的历程-构造函数/抽象类/枚举
- Kotlin学习之函数
- C3P0连接池配置
- 线程之间的同步和互斥
- redis数据批量导入导出
- Android 实现微信支付那些事
- Android View事件分发、拦截、消费机制
- Kotlin构造函数
- navigation返回指定的队列页面
- 第五届“蓝桥杯”全国软件 校内选拔赛试题(Java组)11、(18分) 身份证的奥秘
- 敏捷开发scrum
- 设计模式六大原则(1):单一职责原则
- 用定义列表定义一段文字justify
- 文章标题 Hibernate 1-N 双相关联
- linux下glassfish的安装与配置
- 常用列表