当前位置:网站首页>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!!
边栏推荐
- XSS related knowledge
- 分布式.分布式锁
- Bert usage and word prediction based on Keras_bert model
- Can deep learning solve the parameters of a specific function?
- 华为“天才少年”稚晖君又出新作,从零开始造“客制化”智能键盘
- 响应式布局与px/em/rem的比对
- 【genius_platform软件平台开发】第七十四讲:window环境下的静态库和动态库的一些使用方法(VC环境)
- ShardingSphere之水平分库实战(四)
- C语言_结构体指针数组函数选票系统
- Why use high-defense CDN when financial, government and enterprises are attacked?
猜你喜欢
随机推荐
VS warning LNK4099:未找到 PDB 的解决方案
不用Swagger,那我用啥?
RTL8720DN开发笔记一 环境搭建与mqtt实例
24. Please talk about the advantages and disadvantages of the singleton pattern, precautions, usage scenarios
Why use high-defense CDN when financial, government and enterprises are attacked?
MySQL高级-六索引优化
Rocky/GNU之Zabbix部署(2)
TiDB 操作实践 -- 备份与恢复
tensorflow与GPU版本对应安装问题
DOM系列之 client 系列
BOM系列之Navigator对象
解析云原生消息流系统 Apache Pulsar 能力及场景
The sword refers to offer17---print the n digits from 1 to the largest
MySQL database constraints, table design
调度中心xxl-Job
ROS Action通信
【952. 按公因数计算最大组件大小】
埃拉托斯特尼筛法
ShardingSphere之水平分库实战(四)
typescript10-commonly used basic types