- 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.
- Java完全自學(xué)教程
- Boost C++ Application Development Cookbook(Second Edition)
- Java加密與解密的藝術(shù)(第2版)
- Visual Basic程序設(shè)計(jì)習(xí)題解答與上機(jī)指導(dǎo)
- C語(yǔ)言實(shí)驗(yàn)指導(dǎo)及習(xí)題解析
- Mastering Apache Spark 2.x(Second Edition)
- VMware虛擬化技術(shù)
- HTML5從入門(mén)到精通 (第2版)
- Learning Apache Cassandra
- INSTANT Yii 1.1 Application Development Starter
- Visualforce Developer’s guide
- 匯編語(yǔ)言編程基礎(chǔ):基于LoongArch
- Android嵌入式系統(tǒng)程序開(kāi)發(fā):基于Cortex-A8(第2版)
- Python機(jī)器學(xué)習(xí)算法與應(yīng)用
- 編程改變生活:用Python提升你的能力(進(jìn)階篇·微課視頻版)