官术网_书友最值得收藏!

Static functions

Static functions are functions that can be invoked without creating multiple instances of a class. Static functions avoid code duplication and can be reused.

Let's take a look at how to write a static function in Kotlin.

Consider the following code for 15a_StaticMethods.kts:

object MyUtil {
fun foo(){
println("Static function foo() is invoked")
}
}

MyUtil.foo()

Note that we declared an object MyUtil and defined a function foo(). This is known as object declaration.

We invoked the function foo() directly using the object MyUtil

The output of the preceding code is as follows:

There are different ways to write static functions in Kotlin. We can define a companion object inside a class and define a static function in it. Consider the following code for 15b_StaticMethods.kts:

class Person {
companion object {
fun foo(){
println("Static function foo() is invoked")
}
}
}
Person.foo()

The output is as follows:

We can also give a name to the companion object. Consider the following code for 15c_StaticMethods.kts:

class Person {
companion object Util {
fun foo(){
println("Static function foo() is invoked")
}
}
}
Person.Util.foo()

The output is as follows:

We can invoke the static method shown in the preceding example with  companion as  Person.Companion.foo(). The static method foo can be invoked using either the class name or a named companion object prefixed with the class name, such as Person.Util.foo().

In this section, we have covered the constructs that Kotlin provides. We will be using these constructs in the next few chapters.

主站蜘蛛池模板: 晋宁县| 林芝县| 灵寿县| 明水县| 沾化县| 青川县| 平昌县| 建水县| 子长县| 砚山县| 澎湖县| 镇江市| 深州市| 丽水市| 广昌县| 临猗县| 买车| 礼泉县| 海南省| 泰兴市| 云龙县| 星子县| 五家渠市| 南华县| 铁岭县| 台北市| 平罗县| 松阳县| 石嘴山市| 沅陵县| 怀来县| 南阳市| 安宁市| 马龙县| 涞水县| 望奎县| 乐陵市| 广汉市| 广灵县| 莱州市| 城口县|