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

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.

主站蜘蛛池模板: 固原市| 德昌县| 中超| 华亭县| 金门县| 普洱| 普定县| 尤溪县| 渝北区| 北川| 固原市| 沙洋县| 凤冈县| 屏东县| 三门县| 老河口市| 绿春县| 临颍县| 仪陇县| 宁夏| 武夷山市| 正宁县| 斗六市| 镇江市| 和林格尔县| 淮滨县| 邵东县| 凌云县| 那坡县| 和平县| 淮滨县| 辽源市| 蓝田县| 威海市| 抚顺市| 两当县| 余干县| 乐亭县| 固阳县| 泌阳县| 循化|