Kotlin中的'a?.let {}?:run {}`是惯用语言吗? [英] Is `a?.let{} ?: run{}` idiomatic in Kotlin?

查看:1284
本文介绍了Kotlin中的'a?.let {}?:run {}`是惯用语言吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在S.O中看到以下评论.帖子,我很感兴趣:

I saw the following comment in a S.O. post, and I'm intrigued:

为什么不使用null进行检查? a?.let{} ?: run{}仅在极少数情况下适用,否则不是惯用语言– voddan 16年5月15日在7:29

why don't you use if for null checks? a?.let{} ?: run{} is only appropriate in rare cases, otherwise it is not idiomatic – voddan May 15 '16 at 7:29 best way to null check in kotlin?

为什么该构造仅在少数情况下适用"?
Kotlin的首席工程师说,

Why is that construct "only appropriate in rare cases"?
The lead engineer for Kotlin says,

run允许您在Elvis运算符的右侧使用多个语句 https://stackoverflow.com/a/51241983/6656019

尽管我承认实际上并没有认可它是惯用的.这两个职位似乎都是受人尊敬的S.O. Kotlin贡献者.
激发原始评论的帖子提到,如果a是可变的,则表达式的let部分非常重要.在这种情况下,您将需要a?.let{} ?: run{}而不是if{} else {}.

although I admit that's not actually endorsing it as idiomatic. Both of these posts seem to be from very well respected S.O. Kotlin contributors.
The post that inspired the original comment mentions that the let part of the expression is important if a is mutable. In that case, you'll need a?.let{} ?: run{} instead of if{} else {}.

我发现我喜欢让Elvis运行"的构造.在大多数情况下,我应该避免使用它吗?
感谢您的见识.

I find I like the "let Elvis run" construct. Should I avoid it in most cases?
Thanks for any insight.

推荐答案

在这种情况下,您需要一个?.let {}?:run {}而不是if {} else {}

In that case, you'll need a?.let{} ?: run{} instead of if{} else {}

否,您可以省略run { statement }的运行部分并使用a?.let{} ?: statement.

No, you can omit the run part of run { statement } and use a?.let{} ?: statement.

在大多数情况下应该避免吗?

Should I avoid it in most cases?

您应在需要时使用它.例如.当您想在那种情况下运行多个语句时.需要指出的是,这是一种罕见的情况.通常,您会在elvis运算符的右侧仅看到一条语句.
当然,当您不需要它时也不要使用它.保持代码简单.

You should use it when you need it. E.g. when you want to run multiple statements in that scenario. It is pointed out that that is a rare scenario. Often you will see just a single statement on the right hand side of an elvis operator.
And of course don't use it when you don't need it. Keep the code simple.

这篇关于Kotlin中的'a?.let {}?:run {}`是惯用语言吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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