Kotlin匿名函数用例? [英] Kotlin anonymous function use case?

查看:81
本文介绍了Kotlin匿名函数用例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据我的理解,Kotlin中的匿名函数允许您指定返回类型.除此之外,anonymous内部的return语句将仅退出功能块,而在lambda中,它将退出封闭的功能.

Based on my understanding, anonymous function in Kotlin allow you to specify return type. In addition to that, return statement inside anonymous will exit only the function block, while in lambda it will exit the enclosing function.

还是,我无法想象lambda语法无法提供的Kotlin匿名函数在现实世界中的用例是什么?

Still, I can't imagine what would be the real world use case of anonymous function in Kotlin that lambda syntax cannot provide?

科特林高阶函数和Lambda

推荐答案

用例是有时我们可能希望对返回类型进行明确说明.在这种情况下,我们可以使用所谓的匿名函数.示例:

The use case is that sometimes we may wish to be explicit about the return type. In those cases, we can use so called an anonymous function. Example:

fun(a: String, b: String): String = a + b

或者更好的返回控制,例如:

Or better return control like:

fun(): Int {
    try {
        // some code
        return result
    } catch (e: SomeException) {
        // handler
        return badResult
        }
}

这篇关于Kotlin匿名函数用例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆