Vivek Modi
Vivek Modi

Reputation: 7151

How to pass parameter in function as parameter to another and to create genric function in kotlin

I want to pass parameter in function but it giving error This syntax is reserved for future use; to call a reference, enclose it in parentheses: (foo::bar)(args). Also i want to make a genric runFunction which can take any parameter i.e. Int, String etc. In this example code i am sending sumInt(2) to runFunction also i want to send concatenateString("John"). Anyone Know how to achieve this. I tried search Kotlin: how to pass a function as parameter to another?

][1]

After updating the anwser and using lamba

fun main(vararg args: String) {
    runFunction { sumInt(2) }
    runFunction { concatenateString("John") }
}

fun <T: Any> runFunction(action: () -> (T)) {
    println(action())
}

private fun sumInt(a: Int): Int {
    return a + 2
}

private fun concatenateString(a: String): String {
    return "$a welcome"
}

Upvotes: 0

Views: 1295

Answers (1)

Tenfour04
Tenfour04

Reputation: 93551

You need to wrap the function call in a function if you want to pass parameters along to it. A lambda function is the most concise way.

fun main(vararg args: String) {
    runFunction { sumInt(2) }
}

Upvotes: 1

Related Questions