[Kotlin] Adding functions to existing classes (extension functions)

In Kotlin, you are able to extend a class. Just like add prototype in Javascript.

fun toSentenceCase(a: String): String {
    return a[0].toUpperCase() + a.substring(1)
}

 

We can extend this fun to String:

fun String.toSentenceCase(): String {
    return this.toUpperCase() + this.substring(1)
}

 

Then in the whole package, we able to use that function:

val greeting = "welcome"
println(greeting.toSentenceCase())

 

posted @ 2020-11-01 22:20  Zhentiw  阅读(86)  评论(0)    收藏  举报