Default parameters

Sometimes, it is convenient to provide default values for parameters in a function. Let's say we want to create a thread pool. The parameter to set the number of threads could default to the number of CPU cores. This would be a sensible default, but the user might still want to use something different.

The way to achieve this in languages without default parameters is to offer overloaded versions of the same function:

    fun createThreadPool(): ExecutorService { 
      val threadCount = Runtime.getRuntime().availableProcessors() 
      return createThreadPool(threadCount) 
    } 
 
    fun createThreadPool(threadCount: Int): ExecutorService { 
      return Executors.newFixedThreadPool(threadCount) 
    } 

Here, the user can now choose which version to invoke. However, ...

Get Programming Kotlin now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.