Skip to main content
  1. Posts/

Kotlin miscellinius - Referencing function and using vararg

·404 words·2 mins· loading · loading ·
Programming Kotlin Function Post
luc1d
Author
luc1d
It all started with a pen
Table of Contents

Understanding passing reference of a function
#

Assign a function reference to a variable
#

  • while learning to code in kotlin , I came across a term Referencing a Function Without Calling It using reference operator ( :: ) . One example : when you need to assign a function reference to a variable , assuming you have two functon but cant decide which one to use .

Code :

 1fun main() {
 2    //---- block1 : just passing reference of a function ----
 3    val opinion: Boolean = readln().toBoolean()
 4
 5    val operationToPerform = if (opinion) ::func1 else ::func2 
 6    println("you choose $opinion and the consequence is ${operationToPerform(5, 6)}")
 7}
 8
 9// add two number
10fun func1(num: Int, num2: Int): Int {
11    return num + num2
12}
13
14//multiply 2 number
15fun func2(num: Int, num2: Int): Int {
16    return num * num2
17}

Output :

true
you choose true and the consequence is 11

Passing a function to a function as a reference
#

  • It can also be used to pass a function reference as an argument to another function .

Code :


fun main() {
    funcApply(::funcPrints, "Kotlin")
}


// ----     ----

fun funcPrints(inp: String) {
    println("Hi , $inp")
}

// here funcApply has 2 parameter . func is name of function & it expects (String) parameter .
// using -> to specify return type . in this case Unit or (kotlin.unit)  
             //1 any name.    2- unit must
fun funcApply(func: (String) -> Unit, inp: String) {
    func(inp)
}

Output :

Hi , Kotlin

Usage of vararg and function reference
#

  • Using vararg , a function now can accept multiple argument . funcArgsSum expetcs IntArray (array of int) and returns sum . We need to convert Array<Int> to a vararg Int using the .toIntArray() function . The reason is that vararg in Kotlin expects a parameter of type Int, but Array<Int> is not directly compatible with it. In Kotlin, spread using * can only be used with a vararg parameter of type Int.

Code :


fun main() {
    var arr: Array<Int> = arrayOf(1 , 2 , 3)
    println("Application of vararg. Ans : ${funcArgsSum(*arr.toIntArray())}")
    println("Pass values directly. Ans is same : ${funcApplyArgs(::funcArgsSum, 1 ,2 ,3)}")
}


fun funcArgsSum(vararg num: Int): Int {
    return num.sum()
}

fun funcApplyArgs(func: (IntArray) -> Int, vararg inp: Int):Int {
    return func(inp)
}

Output :


Application of vararg. Ans : 6
Pass values directly. Ans is same : 6

Related

A start of something
·321 words·2 mins· loading · loading
Post Blog Post