kotlin函数的一些用法

测试函数的一些用法:

Kotlin 复制代码
fun main() {
    val func1: (Int, Int) -> Int = ::getMax // ::引用一个函数
    println("max(8, 9) = ${func1(8, 9)}")    
    
    val func2: (Int, Int) -> Int = fun(a: Int, b: Int): Int { // 赋值为一个匿名函数
    	return a + b
	}
    println("sum(8, 9) = ${func2(8, 9)}")    
    
    val func3: (Int, Int) -> Int = { a, b -> if(a < b) a else b } // Lambda表达式函数
    println("min(8, 9) = ${func3(8, 9)}")   
    
    // 函数传参为Lambda表达式
    invoke({name, zuoYouMing -> println("我是$name, 我的座右铭是$zuoYouMing")}, "司徒浩南", "铜锣湾只有一个浩南,就是我司徒浩南!")
}

fun getMax(a: Int, b: Int) = if (a > b) a else b

fun invoke(func: (String, String) -> Unit, str1: String, str2: String) {
    func(str1, str2) // 直接调用参数的函数
}

打印:

ok. 函数用法很灵活。

相关推荐
Kapaseker16 小时前
一杯美式搞定 Kotlin 空安全
android·kotlin
FunnySaltyFish1 天前
什么?Compose 把 GapBuffer 换成了 LinkBuffer?
算法·kotlin·android jetpack
Kapaseker2 天前
Compose 进阶—巧用 GraphicsLayer
android·kotlin
Kapaseker3 天前
实战 Compose 中的 IntrinsicSize
android·kotlin
A0微声z5 天前
Kotlin Multiplatform (KMP) 中使用 Protobuf
kotlin
alexhilton5 天前
使用FunctionGemma进行设备端函数调用
android·kotlin·android jetpack
lhDream5 天前
Kotlin 开发者必看!JetBrains 开源 LLM 框架 Koog 快速上手指南(含示例)
kotlin
RdoZam5 天前
Android-封装基类Activity\Fragment,从0到1记录
android·kotlin
Kapaseker6 天前
研究表明,开发者对Kotlin集合的了解不到 20%
android·kotlin
郑州光合科技余经理6 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php