kotlin函数作为参数和函数作为返回值练习
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) }
-
-
//带参数,参数为msg,有返回值的函数类型为Strnig
-
private var hello : (msg: String) -> String = { "hello ${it.uppercase()}!!" }
-
-
//getIntance返回一个函数,这个函数参数为空,返回值类型为ShoppingMallFloatView
-
fun getInstance(context: Context): () -> ShoppingMallFloatView = {
-
instance ?: synchronized(this) {
-
instance ?: ShoppingMallFloatView(context).also {
-
instance = it
-
}
-
}
-
-
}
-
-
-
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)
-
-
//参数为一个数字 加 一个函数
-
test(2) { a: Int, b: Int ->
-
var num = (a b)*5
-
num
-
}
-
}
-
-
//函数作为参数,返回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)
-
}
-
}
-
-
fun test(a : Int , b : (num1 : Int , num2 : Int) -> Int) : Int{
-
return a b.invoke(3,5) //8
-
}
-
-
}
运行结果:
-
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!!
这篇好文章是转载于:学新通技术网
- 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
- 本站站名: 学新通技术网
- 本文地址: /boutique/detail/tanhgbjhhe
系列文章
更多
同类精品
更多
-
photoshop保存的图片太大微信发不了怎么办
PHP中文网 06-15 -
word里面弄一个表格后上面的标题会跑到下面怎么办
PHP中文网 06-20 -
《学习通》视频自动暂停处理方法
HelloWorld317 07-05 -
photoshop扩展功能面板显示灰色怎么办
PHP中文网 06-14 -
Android 11 保存文件到外部存储,并分享文件
Luke 10-12 -
微信公众号没有声音提示怎么办
PHP中文网 03-31 -
excel下划线不显示怎么办
PHP中文网 06-23 -
excel打印预览压线压字怎么办
PHP中文网 06-22 -
TikTok加速器哪个好免费的TK加速器推荐
TK小达人 10-01 -
怎样阻止微信小程序自动打开
PHP中文网 06-13