Default arguments

We may have a requirement where we want to have an optional parameter for a function. Consider the following example:

fun Int.isGreaterThan(anotherNumber:Int):Boolean { 
    return this>anotherNumber 
} 

We want to make anotherNumber parameter optional; we want it to be 0, if it is not passed as an argument. The traditional way is to have another overloaded function without any parameters, which would call this function with 0, like the following:

fun Int.isGreaterThan(anotherNumber:Int):Boolean { 
    return this>anotherNumber 
} 
fun Int.isGreaterThan():Boolean { 
    return this.isGreaterThan(0) 
} 

However, in Kotlin, things are quite easy and straightforward and they don't require us to define the function again just to make an argument optional. For making arguments optional, Kotlin provides us with default arguments, by which we can specify a default value of a function right away at the time of declaration.

The following is the modified function:

fun Int.isGreaterThan(anotherNumber:Int=0):Boolean { 
    return this>anotherNumber 
} 

We would use the main function as follows:

fun main(args: Array<String>) { 
    println("5>0: ${5.isGreaterThan()}") 
    println("5>6: ${5.isGreaterThan(6)}") 
} 

For the first one, we skipped the argument and for the second one, we provided 6. So, for the first one, the output should be true (as 5 is really greater than 0), while for the second one, it should be false (as 5 isn't greater than 6).

The following screenshot output confirms the same:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.140.197.136