- Hands-On Design Patterns with Kotlin
- Alexey Soshin
- 148字
- 2021-06-25 20:49:26
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.
推薦閱讀
- 黑客攻防從入門(mén)到精通(實(shí)戰(zhàn)秘笈版)
- PWA入門(mén)與實(shí)踐
- Mastering Adobe Captivate 2017(Fourth Edition)
- Python數(shù)據(jù)可視化:基于Bokeh的可視化繪圖
- JavaScript+Vue+React全程實(shí)例
- C和C++游戲趣味編程
- AIRIOT物聯(lián)網(wǎng)平臺(tái)開(kāi)發(fā)框架應(yīng)用與實(shí)戰(zhàn)
- LabVIEW虛擬儀器入門(mén)與測(cè)控應(yīng)用100例
- OpenCV 3 Blueprints
- C++程序設(shè)計(jì)教程(第2版)
- Python預(yù)測(cè)分析與機(jī)器學(xué)習(xí)
- Learning Unreal Engine Game Development
- Android嵌入式系統(tǒng)程序開(kāi)發(fā)(基于Cortex-A8)
- Java程序設(shè)計(jì)入門(mén)(第2版)
- JavaScript編程精解(原書(shū)第3版)