Blu*_*eph 12 null operators kotlin
只有当值不为空时,Kotlin中有一种干净的方法为变量赋值?
例子是:
if(x != null)
y = x
Run Code Online (Sandbox Code Playgroud)
我发现了一个像这样的解
y = x? : return
Run Code Online (Sandbox Code Playgroud)
但我无法理解这是否符合我的要求以及此运算符的工作原理.
Paw*_*wel 27
另一种解决方案,如果你还不想从函数返回:
x?.let{ y = it }
Run Code Online (Sandbox Code Playgroud)
哪个检查是否x为非null,然后将其作为lambda块的唯一参数传递.
如果您x是a,这也是一个安全的电话var.
对于那些搜索并想要一个不会立即返回的解决方案的人。你可以捏住鼻子,这样做:
y = x ?: y
作为一名优秀的程序员,为了满足语法,我不敢为自己分配一个变量。但那是 kotlin 给你的!那些设计师什么都想到了!
小智 5
您的代码完全相同,但编写较少:
if(x != null)
y = x
else
return
Run Code Online (Sandbox Code Playgroud)
使用 Elvis 运算符时,它将 if else 语句缩短为:
y=x ?: return
Run Code Online (Sandbox Code Playgroud)
如果左侧为 true(x 不为空),则将分配 y,否则将执行右侧。
| 归档时间: |
|
| 查看次数: |
5119 次 |
| 最近记录: |