Kotlin教程:扩展函数及示例

2020-04-2311:34:31编程语言入门到精通Comments2,226 views字数 2821阅读模式

Kotlin扩展函数提供了一种向类“添加”方法而不继承类或使用任何类型的设计模式的工具。 创建的扩展函数用作类中的常规函数。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/18304.html

扩展函数使用带有方法名称的前缀接收器类型声明。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/18304.html

fun <class_name>.<method_name>()
Kotlin

在上面的声明中,<class_name>是接收器类型,<method_name>()是扩展函数。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/18304.html

扩展函数声明及用法示例文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/18304.html

通常,从类外部调用已经在类中定义的所有方法。在下面的示例中,Student类声明一个方法是Passed(),它通过创建Student类的student对象,并在main()函数调用。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/18304.html

假设想调用一个没有在Student类中定义的方法(比如isExcellent())。 在这种情况下,在Student类之外创建一个函数(isExcellent())为Student.isExcellent(),并从main()函数调用它。 声明Student.isExcellent()函数称为扩展函数,其中Student类称为接收器类型。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/18304.html

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")
}
Kotlin

执行上面示例代码,得到以下结果 -文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/18304.html

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

以上示例仅演示了如何声明扩展函数。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/18304.html

Kotlin扩展函数示例

下面来看看另一个扩展函数的示例。 在这个例子中,我们使用swap()方法交换MutableList <>的元素。 但是,MutableList <>类在内部不提供swap()方法来交换元素。 为此为MutableList <>创建swap()扩展函数。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/18304.html

列表对象使用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>)扩展函数中列表的索引值。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/18304.html

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")
}
Kotlin

执行上面示例代码,得到以下结果 -文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/18304.html

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

扩展函数作为可空接收器

扩展函数可以定义为可空接收器类型。 即使对象值为null,也可以通过对象变量调用此可空扩展函数。 在函数主体内使用this == null检查对象的可为空性。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/18304.html

下面是使用扩展函数作为可空接收器重写上面示例中的程序。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/18304.html

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")
}
Kotlin

执行上面示例代码,得到以下结果 -文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/18304.html

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

Companion对象扩展

companion对象是在类中声明并使用companion关键字标记的对象。 Companion对象用于直接使用类名称调用类的成员函数(如java中的static关键字)。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/18304.html

包含companion对象的类也可以定义为companion对象的扩展函数和属性。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/18304.html

Companion对象的示例文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/18304.html

在这个例子中,使用类名(MyClass)作为限定符来调用在companion对象内声明的create()函数。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/18304.html

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

执行上面示例代码,得到以下结果 -文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/18304.html

调用创建 companion 对象的方法
Shell

Companion对象扩展示例
下面来看看一个Companion对象扩展的例子。 使用类名作为限定符来调用Companion对象扩展。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/18304.html

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

执行上面示例代码,得到以下结果 -文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/18304.html

执行 companion 对象的扩展

//原文出自【易百教程】,商业转载请联系作者获得授权,非商业转载请保留原文链接:https://www.yiibai.com/kotlin/kotlin-extension-function.html#article-start文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/18304.html

文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/18304.html
  • 本站内容整理自互联网,仅提供信息存储空间服务,以方便学习之用。如对文章、图片、字体等版权有疑问,请在下方留言,管理员看到后,将第一时间进行处理。
  • 转载请务必保留本文链接:https://www.cainiaoxueyuan.com/ymba/18304.html

Comment

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定