kotlin的高阶用法,可以将函数作为参数传入另一个函数内调用,
1、使用 :: 传入函数,带参数和返回值的函数,比如:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
viewModel = ViewModelProvider(this).get(MainViewModel::class.java)
// TODO: Use the ViewModel
// 传入函数参数
printFather(::printSon, "father")
}
/**
* 定义一个函数参数
*/
private fun printFather(method: (String) -> String, str: String) {
Log.d("Alex", str)
Log.d("Alex", method("son"))
// 调用函数的invoke()是一样的
Log.d("Alex", method.invoke("son"))
}
private fun printSon(str: String): String {
return str
}
打印结果:
2023-04-11 08:56:58.273 22645-22645 Alex com.example.myapplication2 D father
2023-04-11 08:56:58.273 22645-22645 Alex com.example.myapplication2 D son
2023-04-11 08:56:58.273 22645-22645 Alex com.example.myapplication2 D son
使用 :: 传入函数,不带参数和返回值的函数,比如:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
viewModel = ViewModelProvider(this).get(MainViewModel::class.java)
// TODO: Use the ViewModel
// 传入函数参数
printFather(::printSon, "father")
}
/**
* 定义一个函数参数
*/
private fun printFather(method: () -> Unit, str: String) {
Log.d("Alex", str)
method()
// 调用函数的invoke()是一样的
method.invoke()
}
private fun printSon() {
Log.d("Alex", "son")
}
打印结果:
2023-04-11 08:52:54.065 22542-22542 Alex com.example.myapplication2 D father
2023-04-11 08:52:54.065 22542-22542 Alex com.example.myapplication2 D son
2023-04-11 08:52:54.065 22542-22542 Alex com.example.myapplication2 D son