Sunday 28 January 2018

Kotlin: Function default arguments

We can specify default values to function parameters. These default values are used, when you do not specify any values to the function arguments while calling.

fun readFile(offset: Int = 0, numOfBytes: Int = 1024) {
         println("Reading file from offset : $offset, numOfBytes : $numOfBytes ")
}

readFile()
Since readFile() called with no arguments, offset and numOfBytes are set to default values.

readFile(10)
Since readFile() called with one argument 10, offset is set to 10 and numOfBytes is set to default value 1024.

readFile(10, 300)
Since readFile() called with two arguments, offset is set to 10 and numOfBytes is set to 1024.  

DefaultValues.kt
fun readFile(offset: Int = 0, numOfBytes: Int = 1024) {
 println("Reading file from offset : $offset, numOfBytes : $numOfBytes ")
}

fun main(args: Array<String>) {
 readFile()
 readFile(10)
 readFile(10, 300)
}

Output
Reading file from offset : 0, numOfBytes : 1024 
Reading file from offset : 10, numOfBytes : 1024 
Reading file from offset : 10, numOfBytes : 300


Named arguments further enhance this feature, when you would like to set the values to some of the arguments and remaining take default values.

readFile(numOfBytes=500)
Since readFile() is called by specifying numOfBytes to 500

FunctionsDemo.kt
fun readFile(offset: Int = 0, numOfBytes: Int = 1024) {
 println("Reading file from offset : $offset, numOfBytes : $numOfBytes ")
}

fun main(args: Array<String>) {
 readFile(numOfBytes=500)
}

Output
Reading file from offset : 10, numOfBytes : 1024, bufferSize : 500



Previous                                                 Next                                                 Home

No comments:

Post a Comment