facebook

Learn about Default function in Kotlin with suitable example here

By Arindam Kundu

Learn about Default function in Kotlin with suitable example here

In Java there is no concept of Default function .If you want to use your default function, which is already used in Kotlin,in your java you need to write @JvmOverloads for interoperability. Let see an example to make out-

Ex-

@file:JvmName(“MyCustomKotlinName”)

fun main(args : Array<String>){

var result = findVolumn(2, 3) //height value has no need to write here

return (result)

}

fun findVolumn(length : Int, breath : Int, height : Int = 10) : Int{ //height is default =10

return length * breath * height ;

}

output :–>

60

If you write height value in your main function that will overrides the previous value of height.

Ex-

fun main(args : Array<String>){

var result = findVolumn(2, 3, 20) // overrides the value of height

return (result)

}

fun findVolumn(length : Int, breath : Int, height : Int = 10) : Int{

return length * breath * height ;

}

output :–>

120

If you want this function in your Java file then you have to write in this way….

i) At first you have to write @JvmOverloads before starting this function.

Ex

@JvmOverloads

fun findVolumn(length : Int, breath : Int, height : Int = 10) : Int{

return length * breath * height ;

}

ii) Then you can call this function in your java file.

Ex

MyCustomKotlinName . findVolumn(2, 3, 10);

Arindam Kundu Subscriber
Android Developer , Openweb Solutions

Android Developer at Openweb Solutions

Posts created 5

Begin typing your search term above and press enter to search. Press ESC to cancel.

Back To Top
shares