Kotlin相当于三元运算符 [英] Kotlin equivalent of ternary operator

查看:131
本文介绍了Kotlin相当于三元运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,在Java中,我们有三元运算符(?),有时它对于简化if-else内联计算的某些值很有用.例如:

So in java we have the ternary operator (?), which sometimes is useful to easy some value computed by a if-else inlines. For example:

myAdapter.setAdapterItems(
            textToSearch.length == 0
            ? noteList
            : noteList.sublist(0, length-5)
)

我知道kotlin中的等效词是:

I know the equivalent in kotlin would be:

myAdapter.setAdapterItems(
                if(textToSearch.length == 0)
                    noteList
                else
                    noteList.sublist(0, length-5) 
)

但是我只是喜欢Java中的三元运算符,用于简短的表达式条件以及将值传递给方法时.有任何Kotlin等效产品吗?

But i just used to love the ternary operator in Java, for short expression conditions, and when passing values to a method. Is there any Kotlin equivalent?

推荐答案

Kotlin中没有三元运算符.

There is no ternary operator in Kotlin.

https://kotlinlang.org/docs/reference/control-flow.html

在Kotlin中,如果是表达式,即返回一个值.因此,没有三元运算符(条件?then:else),因为普通if在此角色下可以正常工作.

In Kotlin, if is an expression, i.e. it returns a value. Therefore there is no ternary operator (condition ? then : else), because ordinary if works fine in this role.

您可以在此处找到更详细的说明.

You can find a more detailed explanation here.

这篇关于Kotlin相当于三元运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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