kotlin 扩展类的功能
扩展功能 (Extension function)
Kotlin provides the ability to add more functionality to the existing class without inheriting them.
Kotlin可以在不继承现有类的情况下为其添加更多功能。
This is done via a special declaration called "Extension'.
这通过称为“扩展”的特殊声明来完成。
When a function added into an existing User-defined or Library class called 'Extension Function'.
当函数添加到现有的用户定义或库类中时,称为“ 扩展函数 ”。
It can also define extensions of functions and properties for companion objects.
它还可以定义伴随对象的功能和属性的扩展。
Kotlin扩展功能功能程序 (Program for extension function features in Kotlin)
package com.includehelp
// Declare class
class MyClass1{
// Member function
fun sayHello(){
println("Say Hello")
}
}
// Declare class
class MyClass2{
// create companion object to call method with class name
companion object{
// companion object function
fun display(){
println("Display from Companion Object !!")
}
}
}
// define Extension function for MyClass1
fun MyClass1.greetExtn(){
println("Greetings from Extension Function !!")
}
// define extension for Int Class
fun Int.isOdd(){
if(this%2==0){
println("Number is ODD")
}
}
// Define Extension function for MyClass2 Companion object
fun MyClass2.Companion.printData(){
println("Extension function for Companion object !!")
}
// Main Function, Entry point of Program
fun main(){
// Create Instance
val myClass1 = MyClass1()
// Called member function of class
myClass1.sayHello()
// Called extension function
myClass1.greetExtn()
// Called Int Class extension Function
24.isOdd()
// Called companion object member function
MyClass2.display()
// Called companion object extension function
MyClass2.printData()
}
Output:
输出:
Say Hello
Greetings from Extension Function !!
Number is ODD
Display from Companion Object !!
Extension function for Companion object !!
翻译自: https://www.includehelp.com/kotlin/extension-function-features.aspx
kotlin 扩展类的功能