个性化阅读
专注于IT技术分析

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("student passing status is $passingStatus")

val excellentStatus = student.isExcellent(95)
println("student excellent status is $excellentStatus")
}

输出:

student passing status is true
student excellent status is true

上面的示例仅演示了如何声明扩展功能。

Kotlin扩展功能示例

让我们看看扩展功能的真实示例。在此示例中, 我们使用swap()方法交换MutableList <>的元素。但是, MutableList <>类在内部不提供swap()方法来交换其元素。为此, 我们使用swap()函数为MutableList <>创建扩展函数。

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

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("before swapping the list :$list")
val result = list.swap(0, 2)
println("after swapping the list :$result")
}

输出:

before swapping the list :[5, 10, 15]
after swapping the list :[15, 10, 5]

扩展功能为可空接收器

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

让我们使用扩展功能作为可为空的接收器重写以上程序。

funMutableList<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("before swapping the list :$list")
val result = list.swap(0, 2)
println("after swapping the list :$result")
}

输出:

before swapping the list :[5, 10, 15]
after swapping the list :[15, 10, 5]

随行对象扩展

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

包含随行对象的类也可以定义为随行对象的扩展功能和属性。

伴随对象的例子

在此示例中, 我们调用在随行对象内部声明的create()函数, 使用类名称(MyClass)作为限定符。

class MyClass {
    companion object {
        fun create():String{
            return "calls create method of companion object"
        }
    }
}
fun main(args: Array<String>){
val instance = MyClass.create()
}

输出:

calls create method of companion object

随播对象扩展示例

让我们看一个伴随对象扩展的例子。还使用类名作为限定符来调用伴随对象扩展。

class MyClass {
    companion object {
        fun create(): String {
            return "calling create method of companion object"
        }
    }
}
fun MyClass.Companion.helloWorld() {
println("executing extension of companion object")
}
fun main(args: Array<String>) {
MyClass.helloWorld() //extension function declared upon the companion object
}

输出:

executing extension of companion object
赞(0)
未经允许不得转载:srcmini » Kotlin扩展功能

评论 抢沙发

评论前必须登录!