欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 游戏 > Kotlin 学习手册01 高阶函数

Kotlin 学习手册01 高阶函数

2024/10/24 9:20:29 来源:https://blog.csdn.net/qq_34814092/article/details/141557284  浏览:    关键词:Kotlin 学习手册01 高阶函数

Kotlin 学习手册01 高阶函数

  • 1 函数作为参数
  • 2 函数作为返回值
  • 3 测试代码

在Kotlin中,高阶函数(Higher-Order Functions)是指接受函数作为参数或返回一个函数的函数。这种特性允许你将函数像变量一样传递,从而使代码更加灵活和可重用。

1 函数作为参数

/*** 函数作为参数*/
fun calculate(x: Int, y: Int, operation: (Int, Int) -> Int): Int {return operation(x, y)
}

2 函数作为返回值

/*** 函数作为返回值*/
fun operation(operation: String): (Int, Int) -> Int {return when (operation) {"addition" -> { a, b -> addition(a, b) }"subtraction" -> { a, b -> subtraction(a, b) }"multiply" -> { a, b -> a * b }"division" -> { a, b -> a / b }else -> { _, _ -> 0 }}
}

3 测试代码


/*** 加法*/
fun addition(a: Int, b: Int): Int = a + b/*** 减法*/
fun subtraction(a: Int, b: Int): Int = a - b/*** 乘法*/
fun multiply(a: Int, b: Int): Int {return a * b
}/*** 除法*/
fun division(a: Int, b: Int): Int {return a / b
}fun main() {// 函数作为参数println(calculate(5, 3, ::addition))println(calculate(5, 3, ::subtraction))println(calculate(5, 3, ::multiply))println(calculate(5, 3, ::division))// 函数作为返回值println(operation("addition")(5, 3))println(operation("subtraction")(5, 3))println(operation("multiply")(5, 3))println(operation("division")(5, 3))
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com