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

Extension functions

You may have noticed from the previous examples that String in Kotlin has some methods that its Java counterpart is lacking, such as reversed(). How is that achieved, if it's the same String type as in Java and, as we know, String in Java cannot be extended by any other class, since it's declared final?

If you look at the source code, you'll find the following:

public inline fun String.reversed(): String {
return (this as CharSequence).reversed().toString()
}

This feature is called an extension function, and it also exists in some other languages, such as C# or Groovy. 

To extend a class without inheriting from it, we prefix the function name, reversed in our example, with a class name we want to extend.

Do note that the extension function cannot override the member function. The inline keyword will be discussed in later chapters.

主站蜘蛛池模板: 汶川县| 桃园市| 江华| 陆丰市| 肇庆市| 莱阳市| 德惠市| 禄丰县| 虹口区| 贵定县| 奉化市| 无极县| 卫辉市| 剑河县| 马边| 积石山| 萨迦县| 满城县| 桂阳县| 大名县| 嘉定区| 南阳市| 桃源县| 绵竹市| 疏勒县| 哈尔滨市| 龙里县| 息烽县| 博湖县| 嘉善县| 长治县| 远安县| 团风县| 长子县| 大方县| 吉林市| 个旧市| 锦屏县| 济源市| 虎林市| 宜兴市|