Kotlin-高阶函数

高阶函数是一个将另一个函数作为参数返回一个函数的函数

object FunctionTest {
    @JvmStatic
    fun main(args: Array<String>) {
        var sumReult = calculate(4,5,::sum)
        println("value = $sumReult")
        //最后一个参数为lambda表达式,可以放到参数外
//        sumReult = calculate(6,7, { a, b -> a * b })
        sumReult = calculate(6,7) { a, b -> a * b }
        println("value = $sumReult")

        val func = calculate2()
        sumReult = func(8,9)
        println("value = $sumReult")
        println("value = ${func(8,9)}")

    }
	//参数是函数
    private fun calculate(x: Int, y: Int, operation: (Int, Int) -> Int): Int {
        return operation(x, y)
    }

	//返回值是函数
    private fun calculate2(): (Int, Int) -> Int {
        return ::sum
    }


    private fun sum(x: Int, y: Int):Int {
         return x * y
    }
}

在这里插入图片描述

Lambda Functions

val upperCase1: (String) -> String = { str: String -> str.uppercase() } // 1

val upperCase2: (String) -> String = { str -> str.uppercase() }         // 2

val upperCase3 = { str: String -> str.uppercase() }                     // 3

// val upperCase4 = { str -> str.uppercase() } //参数必须明确类型        // 4

val upperCase5: (String) -> String = { it.uppercase() }                 // 5
// 只有一个参数可用it代替
val upperCase6: (String) -> String = String::uppercase                  // 6

println(upperCase1("hello"))
println(upperCase2("hello"))
println(upperCase3("hello"))
println(upperCase5("hello"))
println(upperCase6("hello"))
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值