匿名函数

匿名函数

温馨提示:本文最后更新于2025-11-28 11:49:57,某些文章具有时效性,若有错误或已失效,请在下方留言

匿名函数:没有名字的函数。

语法

基本语法

val anonymousFunction = fun(parameters): ReturnType {
    body
    return statement if needed
}

示例代码

val numbers = listOf(1, 2, 3, 4, 5)
val squaredFunction = fun(x: Int): Int {
    return x * x
}
val squaredNumbers = numbers.map(squaredFunction)
println(squaredNumbers) // [1, 4, 9, 16, 25]

匿名函数类型

// 有参数有返回值
val multiply = fun(a: Int, b: Int): Int {
    return a * b
}
println(multiply(2, 3))

// 有参数无返回值
val multiply2 = fun(a: Int, b: Int) {
    println(a * b)
}
multiply2(2, 3)

// 无参数有返回值
val add = fun(): Int {
    return 1 + 2
}
println(add())

// 无参数无返回值
val add2 = fun() {
    println(1 + 2)
}
add2()
© 版权声明
THE END
喜欢就支持一下吧
点赞0赞赏 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容