如何使用Kotlin在Android中传递函数。如果我知道函数的名称,我就可以传递它:
我想传递任何函数,例如:
fun a(b :() -> Unit){
}
fun b(){
}
我想传递任何函数,例如:
fun passAnyFunc(fun : (?) ->Unit){}
fun a(b :() -> Unit){
}
fun b(){
}
fun passAnyFunc(fun : (?) ->Unit){}
您可以按照以下方式使用匿名函数或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")
}
}
something(true) { prinln("bleh") }
- Yaswant Narayansomething()
接受两个参数。一个是布尔值,另一个是函数本身。因此 something()
成为了高阶函数。对于第二个参数,我们传递了一个称为 lambda 的东西,它只是一个用 { ... }
包围的函数体。由于 something()
接受一个函数作为其最后一个参数(大多数高阶函数都是这样),我们可以像我之前的帖子一样在函数调用外部传递 lambda。 - Yaswant Narayan方法作为参数示例:
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)
}
使用接口:
interface YourInterface {
fun functionToCall(param: String)
}
fun yourFunction(delegate: YourInterface) {
delegate.functionToCall("Hello")
}
yourFunction(object : YourInterface {
override fun functionToCall(param: String) {
// param = hello
}
})
首先在Oncreate函数中声明一个lambda函数(没有名称的函数称为lambda函数。它来自kotlin标准库而不是以{}开头的kotlin语言)如下所示:
var lambda={a:Int,b:Int->a+b}
fun Addition(c:Int, lambda:(Int, Int)-> Int){
var result = c+lambda(10,25)
println(result)
}
Addition(10,lambda)// output 45
Unit
的任何函数”? - Sweeper