Kotlin:致Lambda的声明 [英] Kotlin: Statement to Lambda

查看:128
本文介绍了Kotlin:致Lambda的声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何对lambda发表Kotlin声明?

How can I make a Kotlin statement to lambda?

我知道您可以做到:

fun foo() : () -> Unit {
    return { println("Hello World") }
}

//more beautiful:
fun foo() : () -> Unit = { println("Hello World") }

是否也可以创建不带大括号{...}的匿名lambda?

Is it also possible to create an anonymous lambda without the curly brackets {...}?

特别是在switch语句中,用大括号括起来的通常方式看起来不太好.

In particular in a switch statement, the usual way with curly brackets doesn't look good.

fun bar(i: Int) : () -> Unit {

    return when (i) {

        0 -> { { println("Hello") } }

        1 -> { { println("World") } }

        else -> { { println("Bye") } }
    }
}

期待您的回复!

推荐答案

大括号是语法用于lambda表达式,没有它们就无法创建一个.

Curly braces are the syntax for a lambda expression, you can't create one without them.

when语句中,您可以给分支一个块体,然后将lambda作为其最后一个表达式返回,或者您可以让单个表达式分支通过将其包装在括号中来返回一个lambda(否则将是解释为执行花括号内代码的分支):

In a when statement, you can either give your branch a block body, and return the lambda as its last expression, or you can have a single expression branch return a lambda by wrapping it in parentheses (otherwise it would be interpreted as a branch that executes the code inside the braces):

when (x) {
    "block body returning an Int" -> {
        // do stuff
        25
    }
    "block body returning a lambda" -> {
        // do stuff
        { println("Hello") }
    }
    "single expression returning an Int" -> 25
    "single expression returning a lambda" -> ({ println("Hello") })
}

这篇关于Kotlin:致Lambda的声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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