当前位置:网站首页>kotlin中函数作为参数和函数作为返回值实例练习
kotlin中函数作为参数和函数作为返回值实例练习
2022-07-31 01:17:00 【汤米粥】
kotlin中函数作为参数和函数作为返回值,在工作中写代码有时会被卡住,怎么写都提示语法错误,今天专门研究一下几种常用的用法。
package com.example.test
import android.util.Log
import java.util.*
class KotlinSample {
//直接定义函数
//带参数,没有返回值的函数
private var myPrint: (msg: String) -> Unit = { msg -> Log.e("xxx5",msg) }
//带参数,有返回值的函数
private var hello : (msg: String) -> String = { "hello ${it.uppercase()}!!" }
//函数作为参数
fun callMethods() {
method1 {
var hello = "hello world"
Log.e("xxx1", hello)
hello
}
method2 {
var hello = "hello world"
Log.e("xxx2", hello)
}
method3("hello world") { msg ->
Log.e("xxx3", msg)
}
//函数作为返回值
var method4 = method4("hello world")
method4.invoke()
//使用定义的函数
myPrint.invoke("hello world")
var greet = hello("zhang san")
myPrint.invoke(greet)
}
//返回String 但是不需要return 直接将字符串写在最后一行
private fun method1(method: () -> String) {
method.invoke()
}
//Unit表示没有返回值
private fun method2(method: () -> Unit) {
method.invoke()
}
//函数作为参数,有一个输入参数时。不能直接带给它,需要另外一个参数传进来。
private fun <T> method3(msg1: T, method: (msg: T) -> Unit) {
method.invoke(msg1)
}
//函数作为返回值
private fun method4(str: String): () -> Unit {
Log.e("xxx4", "这一部分不返回,直接运行")
return {
var strNew = str.uppercase(Locale.getDefault())
Log.e("xxx4", strNew)
}
}
}
运行结果:
2022-07-28 11:05:04.308 20589-20589/com.example.test E/xxx1: hello world
2022-07-28 11:05:04.308 20589-20589/com.example.test E/xxx2: hello world
2022-07-28 11:05:04.308 20589-20589/com.example.test E/xxx3: hello world
2022-07-28 11:05:04.308 20589-20589/com.example.test E/xxx4: 这一部分不返回,直接运行
2022-07-28 11:05:04.308 20589-20589/com.example.test E/xxx4: HELLO WORLD
2022-07-28 11:05:04.309 20589-20589/com.example.test E/xxx5: hello world
2022-07-28 11:05:04.309 20589-20589/com.example.test E/xxx5: hello ZHANG SAN!!
边栏推荐
- ShardingSphere之公共表实战(七)
- ShardingSphere's unsharded table configuration combat (6)
- 【Demo】ABAP Base64加解密测试
- 35. Reverse linked list
- 孩子的编程启蒙好伙伴,自己动手打造小世界,长毛象教育AI百变编程积木套件上手
- 手把手教你配置Jenkins自动化邮件通知
- tensorflow与GPU版本对应安装问题
- API 网关 APISIX 在Google Cloud T2A 和 T2D 的性能测试
- 人工智能与云安全
- Installation problem corresponding to tensorflow and GPU version
猜你喜欢
随机推荐
【网络安全】文件上传靶场通关(1-11关)
typescript17 - function optional parameters
Detailed explanation of 9 common reasons for MySQL index failure
Rocky/GNU之Zabbix部署(2)
Basic Parameters of RF Devices 1
typescript10-commonly used basic types
使用PageHelper实现分页查询(详细)
图像处理工具设计
VS warning LNK4099: No solution found for PDB
822. Walk the Grid
SWM32 Series Tutorial 6 - Systick and PWM
Image processing tool design
typescript9 - common base types
【Mysql】——索引的深度理解
使用docker安装mysql
Mysql: Invalid default value for TIMESTAMP
BOM系列之Navigator对象
场景之多数据源查询及数据下载问题
倍增、DFS序
System design. Short chain system design