- Kotlin for Enterprise Applications using Java EE
- Raghavendra Rao K
- 268字
- 2021-06-10 18:49:22
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:
In this section, we have covered the constructs that Kotlin provides. We will be using these constructs in the next few chapters.
- Delphi程序設(shè)計(jì)基礎(chǔ):教程、實(shí)驗(yàn)、習(xí)題
- 劍指JVM:虛擬機(jī)實(shí)踐與性能調(diào)優(yōu)
- Learning RxJava
- 精通API架構(gòu):設(shè)計(jì)、運(yùn)維與演進(jìn)
- Oracle數(shù)據(jù)庫(kù)從入門(mén)到運(yùn)維實(shí)戰(zhàn)
- Instant QlikView 11 Application Development
- Symfony2 Essentials
- 區(qū)塊鏈項(xiàng)目開(kāi)發(fā)指南
- Learning VMware vSphere
- Learning Python Data Visualization
- MySQL 8從零開(kāi)始學(xué)(視頻教學(xué)版)
- 計(jì)算機(jī)應(yīng)用基礎(chǔ)(第二版)
- ASP.NET開(kāi)發(fā)寶典
- Visual FoxPro程序設(shè)計(jì)實(shí)驗(yàn)教程
- 中小企業(yè)網(wǎng)站建設(shè)與管理(靜態(tài)篇)