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

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.

主站蜘蛛池模板: 金华市| 德惠市| 确山县| 黎川县| 隆子县| 无锡市| 成都市| 陇南市| 交城县| 内黄县| 治多县| 长治县| 远安县| 吉木乃县| 江城| 清原| 盖州市| 永年县| 黑龙江省| 平果县| 阿瓦提县| 姜堰市| 酉阳| 玛沁县| 瑞金市| 栖霞市| 鄂尔多斯市| 武乡县| 西城区| 阿拉善右旗| 土默特右旗| 航空| 东莞市| 莱州市| 前郭尔| 绵阳市| 梨树县| 怀集县| 建昌县| 光山县| 兴海县|