- 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.
- Learning Python Web Penetration Testing
- Software Testing using Visual Studio 2012
- Unity 2020 Mobile Game Development
- 程序員數學:用Python學透線性代數和微積分
- 跟小海龜學Python
- 概率成形編碼調制技術理論及應用
- 單片機C語言程序設計實訓100例
- Spring MVC+MyBatis開發從入門到項目實踐(超值版)
- Visual Basic程序設計(第三版)
- TypeScript 2.x By Example
- Python+Office:輕松實現Python辦公自動化
- Visual Basic程序設計基礎
- C/C++代碼調試的藝術
- 前端程序員面試算法寶典
- Flutter for Beginners