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

Companion object extensions

Extension functions can also be added to companion objects. They would then be invoked on the companion object rather than on instances of the class.

One example of where this might be useful is when you are adding factory functions to a type. For example, we might wish to add a function to integers in order to return a different random value upon each invocation:

    fun Int.Companion.random(): Int { 
      val random = Random() 
      return random.nextInt() 
    } 

Then, we can invoke the extension function as normal, without needing the Companion keyword:

    val int = Int.random()

This isn't as useful as regular extension functions. This is because we can always create a new object and put the function in there or create a top-level function. But you may wish to associate a function with some other type's namespace. As in the preceding example, a random() function invoked on the Int type is more intuitive than the same function on a class with a name such as IntFactory or RandomInts.

主站蜘蛛池模板: 伊通| 无为县| 监利县| 陆丰市| 嘉定区| 防城港市| 任丘市| 和平县| 沿河| 巢湖市| 济南市| 青铜峡市| 开化县| 随州市| 江达县| 林西县| 陕西省| 敖汉旗| 乌拉特后旗| 苍溪县| 施秉县| 祁连县| 浮山县| 金平| 贡觉县| 平乐县| 滨州市| 镇康县| 德安县| 临沂市| 休宁县| 冷水江市| 沅江市| 漳浦县| 通州区| 宕昌县| 盐亭县| 莒南县| 石林| 察隅县| 富阳市|