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

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.

主站蜘蛛池模板: 龙山县| 莒南县| 安阳县| 平陆县| 禹州市| 灵台县| 绍兴县| 轮台县| 连江县| 南和县| 仁怀市| 灌云县| 尖扎县| 缙云县| 鹿泉市| 辛集市| 吉首市| 迭部县| 南充市| 云浮市| 南投市| 阿勒泰市| 门源| 永登县| 依安县| 宁南县| 科尔| 嘉鱼县| 麦盖提县| 宁陵县| 横山县| 本溪市| 皮山县| 宾阳县| 思茅市| 宁国市| 芜湖县| 宝丰县| 巢湖市| 基隆市| 右玉县|