Ska*_*mar 1 parameters android function kotlin
如何使用Kotlin在android中传递一个函数.如果我知道这样的功能,我能够通过:
fun a(b :() -> Unit){
}
fun b(){
}
Run Code Online (Sandbox Code Playgroud)
我想传递任何函数,如 - >
fun passAnyFunc(fun : (?) ->Unit){}
Yas*_*yan 14
您可以使用匿名函数或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")
}
}
Run Code Online (Sandbox Code Playgroud)
方法作为参数示例:
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)
}
Run Code Online (Sandbox Code Playgroud)