Function Tricks

Function Tricks

  • In same program or class we can’t Define two function with same name
  • It will cause compilation error because compiler can not set two different set of statement to the same name.
  • To solve this error we can change one of the function name
  • OR we can use ⤵️ this.
 

Function Overloading Methods:

  1. Same Name different parameters:
      • Either number of parameter is different
      • OR parameters types are different
       

⇒ number of parameter is different :

 

⇒ parameters types are different:

fun main() { printLn(addition( 1, 2)) printLn(addition( 1.0, 2.0)) } fun addition(a: Int, b: Int) : Int { return a + b } fun addition(a:Double, b:Double) :Double { return a + b }
 

⇒ Named Argumets:

  • when our calling function passing two or more argument but we want set which parameter get this argument perticularly
  • Then we can set named argument
  • we Can give argument in any order
  • Its value will only be assigned to that parameter that we have named / Defined.
 
fun main(){ println(addition(a = 20 , b = 30)) // 50 println(addition(b = 30 , a = 70)) // 70 } fun addition(a: Int, b: Int) : Int { return a + b }
 

⇒ Store function in addition addition Variable:

  • In Kotlin we can store whole function prototype in variable
  • with the help of Scope resolution Operator ::
  • its same as giving refence of function to the variable or giving alias name of the function
 
fun main(){ var fn = ::addition println(fn(3.0 , 7.0)) // 10.0 println(fu(25.0 , 25.0)) // 50.0 } fun addition(a:Double, b:Double) :Double { return a + b }