[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())
原文地址:https://www.cnblogs.com/Answer1215/p/13912039.html