如何在Kotlin中将函数作为参数传递-Android [英] How to pass a function as parameter in kotlin - Android

查看:195
本文介绍了如何在Kotlin中将函数作为参数传递-Android的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用Kotlin在android中传递函数.如果我知道像这样的功能,我就可以通过:

How to pass a function in android using Kotlin . I can able to pass if i know the function like :

fun a(b :() -> Unit){
}
fun b(){
}

我想传递任何类似->
的函数 fun passAnyFunc(fun : (?) ->Unit){}

I want to pass any function like ->
fun passAnyFunc(fun : (?) ->Unit){}

推荐答案

方法作为参数示例:

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)
}

这篇关于如何在Kotlin中将函数作为参数传递-Android的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆