kotlin if(bar == null)vs. bar ?: run

时间:2017-12-31 03:56:38

标签: kotlin

这是样本

bar ?: run {
    // do something. 
}

VS

library(tidyverse)

fils <- list.files("~/Development", pattern="pdf$", full.names = TRUE, recursive = TRUE)

data_frame(
  dir = dirname(fils)
) %>% 
  count(dir) %>% 
  mutate(dir = map_chr(dir, digest::digest)) # you don't need to see my dir names so just remove this from your work

## # A tibble: 14 x 2
##                                 dir     n
##                               <chr> <int>
##  1 06e6c4fed6e941d00c04cae3bd24888b    18
##  2 98bf27d6686a52772cb642a136473d86     9
##  3 c07bfc45ce148933269d7913e1c5e833     1
##  4 84088c9c18b0eb10478f17870886b481     1
##  5 baeb85661aad8bff2f2b52cb55f14ede     1
##  6 c484306deae0a70b46854ede3e6b317a    22
##  7 70750a506855c6c6e09f8bdff32550f8     4
##  8 8c5cbe2598f1f24f1549aaafd77b14c9     1
##  9 9008083601c1a75def1d1418d8acf39e     1
## 10 0c25ef8d27250f211d56eff8641f8beb     1
## 11 3e30987a34a74cb6846abc51e48e7f9e     1
## 12 e71c330b185bf4974d26d5379793671b     1
## 13 fe2e8912e58ba889cf7c6c3ec565b2ee     4
## 14 e07698c59f5c11ac61e927e91c2e8493    27
  1. 哪一个是最佳做法?
  2. 什么是变异财产?
  3. 第一个人是否正在改变财产?

1 个答案:

答案 0 :(得分:0)

  

哪一个是最佳做法?

正如Oliver所指出的,使用if(bar == null)时意图最为明确。这也是Checking for null conditions下官方Kotlin文档中使用的方法。

虽然在这种情况下我不建议,Kotlin允许你做这样的好事:

inline fun whenNull(input: Any?, block: () -> Unit) {
    if(input == null) block()
}

允许您将if(bar == null)重写为:

whenNull(bar) {
    // Do something
}
  

什么是变异属性?

它是一个可以改变其值的变量。基本上,变量是使用var而不是val声明的。

  

第一个选择使用变异属性?

这与您的示例无关,因为您正在检查if(bar == null)

如果您正在查看if(bar != null),那么您所指的是相关的。在这种情况下,如果barvar,则Kotlin无法将其转换为非null类型,因为if的正文中bar的值为if可以随时改变。这意味着在bar的正文中,您必须在?.!!)上进行安全通话,或使用val b = bar if(b != null) { // b has been smart cast to a non-null type }

您可以通过执行以下操作来解决此问题:

b

Kotlin能够将if智能转换为val正文中的非空类型,因为它是不可变的(let)。

或者,您可以使用安全调用和this,它以this值作为参数调用指定的函数/块并返回其结果。鉴于安全通话,bar?.let { // this is bar (non-null) } 当然是非空的。

foreach($s in $fs){
    $s.Volumes | Select-Object @{n='Machine'; e={$s.ServerName}}, Share, FileWalkMethod | Export-CSV D:\data\splunk\otl_varonis\otl_varonis_monitoring.csv -NoTypeInformation -Append
}