Default arguments in Functions

You can specify a default value for a function parameter. The default value is used when the corresponding value is omitted from the function call.

fun main(args:Array<String>)
{
    println( findVolume(5,5))//5*5*20 //Here the 3rd parameter it will take default
                                        parameter value    println(findVolume(5,5,5))//5*5*5 //Here the 3rd parameter replaced the default 
                                        value}

fun  findVolume(length:Int,width:Int,height:Int=20):Int
{
    return length*width*height
}


Output:
500
125

Can  we call default functions from Java file?
Yes, Java  doesn't have any default parameter functions for this we have to use jvm annotations
@JVMOverloads this will give the interoperability between java class file and kotlin file.

Volume.Kt
fun main(args:Array<String>)
{
    println( findVolume(5,5))//5*5*20    println(findVolume(5,5,5))//5*5*5}

fun  findVolume(length:Int,width:Int,height:Int=20):Int
{
    return length*width*height
}

Findvolume.java

import kotlin.jvm.JvmOverloads;

public class FindVolume {
    public static  void main(String[] args)
    {
        VolumeKt.findVolume(5,5);//This will give error because java doesn't support
                                   default parameter functions 
                                   
    }

}


Volume.Kt

fun main(args:Array<String>)
{
    println( findVolume(5,5))//5*5*20    println(findVolume(5,5,5))//5*5*5}
@JvmOverloads
fun findVolume(length:Int,width:Int,height:Int=20):Int { return length*width*height }

Findvolume.java

import kotlin.jvm.JvmOverloads;

public class FindVolume {
    public static  void main(String[] args)
    {
      int result=  VolumeKt.findVolume(5,5);//This will support default parameter 
                                   functions with @Jvmoverloads annotation 
                                   in kotlin file//5*5*20
      System.out.print(result);
                                   
    }

}
Output:
500

Comments