我想传递任何函数,如 - > fun passAnyFunc(fun : (?) ->Unit){}
3 回答
11
使用界面:
interface YourInterface {
fun functionToCall(param: String)
}
fun yourFunction(delegate: YourInterface) {
delegate.functionToCall("Hello")
}
yourFunction(object : YourInterface {
override fun functionToCall(param: String) {
// param = hello
}
})
1
方法作为参数示例:
fun main(args: Array<String>) {
// Here passing 2 value of first parameter but second parameter
// We are not passing any value here , just body is here
calculation("value of two number is : ", { a, b -> a * b} );
}
// In the implementation we will received two parameter
// 1. message - message
// 2. lamda method which holding two parameter a and b
fun calculation(message: String, method_as_param: (a:Int, b:Int) -> Int) {
// Here we get method as parameter and require 2 params and add value
// to this two parameter which calculate and return expected value
val result = method_as_param(10, 10);
// print and see the result.
println(message + result)
}
0
您可以使用匿名函数或lambda,如下所示
fun main(args: Array<String>) {
fun something(exec: Boolean, func: () -> Unit) {
if(exec) {
func()
}
}
//Anonymous function
something(true, fun() {
println("bleh")
})
//Lambda
something(true) {
println("bleh")
}
}
3 回答
使用界面:
方法作为参数示例:
您可以使用匿名函数或lambda,如下所示