kotlin 构造

来源:互联网 发布:知乎入门级古典音乐 编辑:程序博客网 时间:2024/06/01 08:37

构造函数

-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

当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    //。。。}
  • 1
  • 2
  • 3

-------------------------------------------------------------------------------------------------------------------------------


2、当不在主函数中声明时,只能在初始化块以及属性声明中使用
这里写图片描述


-------------------------------------------------------------------------------------------------------------------------------

2、次构造函数

1、次构造函数不能有声明 val 或 var
2、如果类有一个主构造函数(无论有无参数),每个次构造函数需要直接或间接委托给主构造函数,用this关键字

class Person {    constructor() {    }    constructor(name: String):this() {    }    constructor(name: String, age: Int) : this(name) {    }}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
class Customer(){    constructor(name: String):this() {    }    constructor(name: String, age: Int) : this(name) {    }}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

-------------------------------------------------------------------------------------------------------------------------------


3、当没有主构造参数时,创建次构造函数
正确使用:

class Customer{    constructor(name: String) {    }    constructor(name: String, age: Int) : this(name) {    }}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

错误使用:

class Customer{    //没有主构造函数,使用委托this()错误    constructor(name: String) : this() {    }    constructor(name: String, age: Int) : this(name) {    }}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

3、构造函数的使用

两种构造函数结果相同,调用时都可直接调用,或传递一个参数或两个参数进行调用

class Test{    init{        test()        test2()    }    fun test(){        Person()        Person("李四")        Person("李四",18)    }    fun test2(){        Customer()        Customer("李四")        Customer("李四",18)    }}
原创粉丝点击