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

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.

主站蜘蛛池模板: 开阳县| 肃北| 克拉玛依市| 如皋市| 元谋县| 霍城县| 莫力| 昆山市| 司法| 多伦县| 宁城县| 安塞县| 和静县| 美姑县| 若羌县| 溆浦县| 永吉县| 苗栗县| 五华县| 祁门县| 黄浦区| 定日县| 辽宁省| 镇巴县| 商都县| 永丰县| 龙海市| 北碚区| 刚察县| 汤原县| 鞍山市| 兴山县| 罗江县| 桐梓县| 肥城市| 诏安县| 中阳县| 乌苏市| 衡东县| 弋阳县| 攀枝花市|