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

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.

主站蜘蛛池模板: 奎屯市| 蕲春县| 团风县| 从化市| 江门市| 玉环县| 西青区| 宁河县| 永兴县| 西盟| 丹东市| 马关县| 岳西县| 杭锦后旗| 堆龙德庆县| 林州市| 大悟县| 剑河县| 茌平县| 宝山区| 海伦市| 五寨县| 浠水县| 墨玉县| 通河县| 榕江县| 隆尧县| 云霄县| 五常市| 敦煌市| 营山县| 新平| 昭觉县| 福清市| 定西市| 海盐县| 施甸县| 诸暨市| 宜黄县| 威信县| 西乌|