kotlin 扩展类的功能_Kotlin中的扩展功能

kotlin 扩展类的功能

Kotlin language supports the ability to extend a class with new functionality without implementing the inheritance concept by a class or using design pattern such as Decorator. This is accomplished via special indications, which is called Extension Function. Thus, this capability could be effective for becoming code more cleaner and easy to read, and it reduces the code as well. This essay aims to consider Extension Function in Kotlin as an ability for following some best practices in Android development.

Kotlin语言支持使用新功能扩展类的能力,而无需通过类或使用诸如Decorator之类的设计模式来实现继承概念。 这是通过特殊指示(称为扩展功能)完成的。 因此,此功能可以有效地使代码变得更加简洁和易于阅读,并且还可以减少代码。 本文旨在将Kotlin中的扩展功能视为遵循Android开发中一些最佳实践的能力。

Extension Function的解释是什么? (What is the definition of Extension Function?)

Fundamentally, an extension function is a member function of a class, which is defined outside the class. For instance, if you need to use a method to the String class that returns a new string with first and last character removed, you can write an extension method for it. In fact, this method is not already available in String class.

从根本上说,扩展函数是类的成员函数,它是在类外部定义的。 例如,如果需要在String类中使用一种方法,该方法返回删除了第一个和最后一个字符的新字符串,则可以为其编写扩展方法。 实际上,此方法在String类中尚不可用。

使用扩展功能的优点 (Advantages of using Extension Function)

In general, Extension functions have the potential to make your code more brief, readable, and logical by improving and removing boilerplate code from your project. Besides, less code means fewer opportunities for making errors.In addition to previous reasons:

通常,扩展功能可以通过改进和删除项目中的样板代码来使代码更简短,可读性和逻辑性更高。 此外,更少的代码意味着更少的出错机会。

  1. It can be able to add functionality to a final class. It means the class do not need to be defined as a non-final class.

    它可以为最终课程添加功能。 这意味着不需要将类定义为非最终类。
  2. It can be able to add functionality without sub-classing, which means the object reference and the its implementation can be mentioned in your base class.

    它无需子类就可以添加功能,这意味着可以在基类中提及对象引用及其实现。
  3. It follows some best practices in Object-Oriented programming particularly Open–closed principle (in SOLID principles), which is indicated entities (classes, modules, functions, etc.) should be open for extension, but closed for modification.

    它遵循面向对象编程中的一些最佳实践,尤其是“开放-封闭”原则(在SOLID原则中),该原则指示实体(类,模块,函数等)应该开放以进行扩展,但封闭以进行修改。

Kotlin扩展功能 (Kotlin Extension Function)

Basically, Kotlin Extension Function provides a facility to add methods to class without inheriting a class or using any type of design pattern. The created extension functions are used as a regular function inside that class. The extension function is declared with using a prefix receiver type (class name) and also with using method name (extension function) as follows:

基本上,Kotlin扩展功能提供了一种在不继承类或使用任何类型的设计模式的情况下向类添加方法的功能。 创建的扩展函数在该类中用作常规函数。 使用前缀接收器类型(类名)和方法名称(扩展函数)声明扩展函数,如下所示:

fun <class_name>.<method_name>()

Generally, we call all methods from outside the class which are already defined inside the class. For instance, suppose that we want to call a method perimeter() of Circle class which is not defined in class. This indication Circle.perimeter() function is known as extension function, and Circle class is known as receiver type as well.

通常,我们从类外部调用已经在类内部定义的所有方法。 例如,假设我们要调用Circle类中未在类中定义的方法perimeter()。 该指示Circle.perimeter()函数称为扩展函数,Circle类也称为接收器类型。

class Circle(val radius: Double){ 
fun area(): Double{ return Math.PI * radius * radius;
}
} fun Circle.perimeter(): Double{ return 2 * Math.PI * radius;
}fun main(args: Array<String>){
val circle = Circle(5.5);
val perimeterValue = circle.perimeter()
println("Perimeter: $perimeterValue") val areaValue = circle.area()
println("Area: $areaValue")}

扩展库类 (Extended Library Classes)

In Kotlin, you can extend the library classes as well as user-defined classes. In fact, the extension function could be added to library classes, and used in a same way as for user-defined classes similarly. For example:

在Kotlin中,您可以扩展库类以及用户定义的类。 实际上,可以将扩展功能添加到库类中,并以与用户定义类相同的方式使用。 例如:

fun main(args: Array<String>){ 
fun Int.abs() : Int{
return if(this < 0) }
println((-4).abs())
println(4.abs()) }

可空接收器 (Nullable Receiver)

Extension functions can be defined with the class type, which is nullable. In this situation, the check for null is added inside the extension function, and the appropriate value is returned. For instance, we are swapping the elements of Mutable List by using swap() method, but MutableList class does not support the swap() internally. Therefore, for addressing this issue, we should write an extension function for MutableList via swap() function.

扩展函数可以使用可为空的类类型定义。 在这种情况下,对null的检查将添加到扩展函数中,并返回适当的值。 例如,我们使用swap()方法交换Mutable List的元素,但是MutableList类在内部不支持swap()。 因此,为解决此问题,我们应该通过swap()函数为MutableList编写扩展函数。

funMutableList<Int>?.swap(first: Int, second: Int): Any{ 
if (this == null) return "null" //Checked the null-ability here!
else{
val temp = this[first]
this[first] = this[second]
this[second] = temp
return this }
} fun main(args: Array<String>){ val list = mutableListOf(6,9,7)
println("Print the list :$list") val result = list.swap(0, 2)
println("swapping the list :$result") //Output: [7, 10, 6]}

伴侣对象扩展 (Companion Object Extensions)

As a matter of fact, a companion object is an object that is mentioned inside a class and specified with the companion keyword. Companion object is used to call the member function of class directly by using the class name in similar way to static keyword in Java. If a class includes companion object, we can define extension functions and properties for the companion object.

实际上,伴随对象是在类内部提到并使用同伴关键字指定的对象。 伴侣对象用于通过直接使用类名来调用类的成员函数,方法类似于Java中的static关键字。 如果一个类包含伴随对象,我们可以为伴随对象定义扩展功能和属性。

class SampleClass{
companion object{ fun display():String{
return "Companion Object Extensions"
}
}
}
fun main(args: Array<String>){
val instance = SampleClass.display()
}

Furthermore, the companion object extension is being called by using the class name (qualifier). For example:

此外,通过使用类名(限定符)来调用伴随对象扩展。 例如:

class SampleClass{      companion object{        fun create(sample :String): String{ 
return sample
}
}
} fun SampleClass.Companion.printString(){ println("Companion Object Extensions")
}fun main(args: Array<String>){ val sampleObject = SampleClass.printString("Print the string")
println(sampleObject)
}

In conclusion, Kotlin supports the ability to extend a class with new functionality without implementing the inheritance or using a design pattern design pattern. This is accomplished via special indications that is called Extension Function. This ability could be helpful for becoming code more cleaner and easy to read, and it reduces the code as well. However, this method has some negative consequences. For instance, you cannot access the protected properties or functions of your base class.

总之, Kotlin支持使用新功能扩展类的能力,而无需实现继承或使用设计模式设计模式。 这通过称为扩展功能的特殊指示来完成。 此功能可能有助于使代码更简洁易读,并且还减少了代码。 但是,这种方法会带来一些负面影响。 例如,您不能访问基类的受保护属性或函数。

翻译自: https://medium.com/kayvan-kaseb/extension-function-in-kotlin-ef52e4319e81

kotlin 扩展类的功能

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值