Kotlin - 扩展函数

Kotlin - 扩展函数 首页 / Kotlin入门教程 / 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类称为接收器类型。

链接:https://www.learnfk.comhttps://www.learnfk.com/kotlin/kotlin-extension-function.html

来源:LearnFk无涯教程网

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,也可以通过对象变量调用此可为空的扩展函数。使用此== 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

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

微服务架构实战160讲 -〔杨波〕

Go语言核心36讲 -〔郝林〕

玩转webpack -〔程柳锋〕

正则表达式入门课 -〔涂伟忠〕

手把手带你搭建秒杀系统 -〔佘志东〕

编程高手必学的内存知识 -〔海纳〕

大厂设计进阶实战课 -〔小乔〕

B端体验设计入门课 -〔林远宏(汤圆)〕

结构写作力 -〔李忠秋〕

好记忆不如烂笔头。留下您的足迹吧 :)