- 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.
推薦閱讀
- Boost.Asio C++ Network Programming(Second Edition)
- Oracle WebLogic Server 12c:First Look
- FreeSWITCH 1.6 Cookbook
- The Computer Vision Workshop
- CouchDB and PHP Web Development Beginner’s Guide
- 劍指MySQL:架構(gòu)、調(diào)優(yōu)與運維
- 從Java到Web程序設(shè)計教程
- 青少年信息學競賽
- Learning Unreal Engine Android Game Development
- Python語言實用教程
- Android傳感器開發(fā)與智能設(shè)備案例實戰(zhàn)
- ExtJS Web應(yīng)用程序開發(fā)指南第2版
- Java并發(fā)編程:核心方法與框架
- HTML+CSS+JavaScript網(wǎng)頁制作:從入門到精通(第4版)
- 微前端設(shè)計與實現(xiàn)