- Learn Kotlin Programming(Second Edition)
- Stephen Samuel Stefan Bocutiu
- 240字
- 2021-06-24 14:13:37
Member extension functions
Extension functions are usually declared at the top level, but we can define them inside classes as members. This may be used if we want to limit the scope of an extension:
class Mappings { private val map = hashMapOf<Int, String>() private fun String.stringAdd(): Unit { map.put(hashCode(), this) } fun add(str: String): Unit = str.stringAdd() }
In this example, we have defined an extension function that adds a string to hashmap. The second function just invokes this extension function. This roundabout way of adding to hashmap indicates how receivers work in member extension functions.
The hashCode function is defined on Any, and so it exists on the Mappings and String classes through inheritance. When hashCode is invoked in the extension function, there are two possible functions in scope that could be used. The first function in the Mappings instance is called the dispatch receiver. The second function on the string instance is called the extension receiver.
When we have this kind of name shadowing, the compiler defaults to the extension receiver. In the previous example, the hash code used will be the hash code of the string instance. To use the dispatch receiver, we must use a qualified this:
class Mappings { private val map = hashMapOf<Int, String>() private fun String.stringAdd(): Unit { map.put(this@Mappings.hashCode(), this) } fun add(str: String): Unit = str.stringAdd() }
In this second example, the hashCode function will be invoked on the Mappings instance.
- ASP.NET Core:Cloud-ready,Enterprise Web Application Development
- Dynamics 365 for Finance and Operations Development Cookbook(Fourth Edition)
- 基于粒計算模型的圖像處理
- Apache Oozie Essentials
- Power Up Your PowToon Studio Project
- Arduino開發實戰指南:LabVIEW卷
- Getting Started with CreateJS
- Python數據分析(第2版)
- Magento 1.8 Development Cookbook
- Hands-On Enterprise Automation with Python.
- C程序設計案例教程
- BIM概論及Revit精講
- HTML 5與CSS 3權威指南(第3版·上冊)
- SQL Server實用教程(SQL Server 2008版)
- Qlik Sense? Cookbook