Kotlin扩展函数

Kotlin扩展函数提供了一种向类“添加”方法而不继承类或使用任何类型的设计模式的工具。 创建的扩展函数用作类中的常规函数。

扩展函数使用带有方法名称的前缀接收器类型声明。

fun <class_name>.<method_name>()

在上面的声明中,<class_name>是接收器类型,<method_name>()是扩展函数。

扩展函数声明及用法示例

通常,从类外部调用已经在类中定义的所有方法。在下面的示例中,Student类声明一个方法是Passed(),它通过创建Student类的student对象,并在main()函数调用。

假设想调用一个没有在Student类中定义的方法(比如isExcellent())。 在这种情况下,在Student类之外创建一个函数(isExcellent())为Student.isExcellent(),并从main()函数调用它。 声明Student.isExcellent()函数称为扩展函数,其中Student类称为接收器类型。

class Student{
    fun isPassed(mark: Int): Boolean{
        return mark>40
    }
}
fun Student.isExcellent(mark: Int): Boolean{
    return mark > 90
}
fun main(args: Array<String>){
    val student = Student()
    val passingStatus = student.isPassed(55)
    println("学生通过状态是: $passingStatus")

    val excellentStatus = student.isExcellent(95)
    println("学生优秀的状态是:$excellentStatus")
}

执行上面示例代码,得到以下结果 -

学生通过状态是: true
学生优秀的状态是:true

以上示例仅演示了如何声明扩展函数。

Kotlin扩展函数示例

下面来看看另一个扩展函数的示例。 在这个例子中,我们使用swap()方法交换MutableList <>的元素。 但是,MutableList <>类在内部不提供swap()方法来交换元素。 为此为MutableList <>创建swap()扩展函数。

列表对象使用list.swap(0,2)函数调用扩展函数(MutableList <Int> .swap(index1:Int,index2:Int):MutableList <Int>).swap(0,2)swap(0,2)函数传递MutableList <Int> .swap(index1:Int,index2:Int):MutableList <Int>)扩展函数中列表的索引值。

fun MutableList<Int>.swap(index1: Int, index2: Int):MutableList<Int> {
    val tmp = this[index1] // 'this' represents to the list
    this[index1] = this[index2]
    this[index2] = tmp
    return this
}
fun main(args: Array<String>) {
    val list = mutableListOf(5,10,15)
    println("在交换列表之前 :$list")
    val result = list.swap(0, 2)
    println("在交换列表之后 :$result")
}

执行上面示例代码,得到以下结果 -

在交换列表之前 :[5, 10, 15]
在交换列表之后 :[15, 10, 5]

扩展函数作为可空接收器

扩展函数可以定义为可空接收器类型。 即使对象值为null,也可以通过对象变量调用此可空扩展函数。 在函数主体内使用this == null检查对象的可为空性。

下面是使用扩展函数作为可空接收器重写上面示例中的程序。

fun MutableList<Int>?.swap(index1: Int, index2: Int): Any {
    if (this == null) return "null"
    else  {
        val tmp = this[index1] // 'this' represents to the list
        this[index1] = this[index2]
        this[index2] = tmp
        return this
    }
}
fun main(args: Array<String>) {
    val list = mutableListOf(5,10,15)
    println("在交换列表之前 :$list")
    val result = list.swap(0, 2)
    println("在交换列表之后 :$result")
}

执行上面示例代码,得到以下结果 -

在交换列表之前 :[5, 10, 15]
在交换列表之后 :[15, 10, 5]

Companion对象扩展

companion对象是在类中声明并使用companion关键字标记的对象。 Companion对象用于直接使用类名称调用类的成员函数(如java中的static关键字)。

包含companion对象的类也可以定义为companion对象的扩展函数和属性。

Companion对象的示例

在这个例子中,使用类名(MyClass)作为限定符来调用在companion对象内声明的create()函数。

class MyClass {
    companion object {
        fun create():String{
            return "调用创建 companion 对象的方法"
        }
    }
}
fun main(args: Array<String>){
    val instance = MyClass.create()
    println(instance)
}

执行上面示例代码,得到以下结果 -

调用创建 companion 对象的方法

Companion对象扩展示例
下面来看看一个Companion对象扩展的例子。 使用类名作为限定符来调用Companion对象扩展。

class MyClass {
    companion object {
        fun create(): String {
            return "调用 companion 对象的create方法"
        }
    }
}
fun MyClass.Companion.helloWorld() {
    println("执行 companion 对象的扩展")
}
fun main(args: Array<String>) {
    MyClass.helloWorld() // 在 companion 对象上声明的扩展函数
}

执行上面示例代码,得到以下结果 -

执行 companion 对象的扩展

上一篇:Kotlin Sealed类

下一篇:Kotlin泛型

关注微信小程序
程序员编程王-随时随地学编程

扫描二维码
程序员编程王

扫一扫关注最新编程教程