detekt/detekt

Suggest to use `if` and `when` as expression when applicable

オープン

#6,233 opened on 2023/06/24

 (2 件のコメント) (2 件のリアクション) (0 人の担当者)Kotlin (834 件のフォーク)batch import
help wantedrules

Repository metrics

Stars
 (6,942 個のスター)
PR merge metrics
 (平均マージ 4d 9h) (30d で 65 merged PRs)

説明

Expected Behavior of the rule

Prohibit usage of if or when like below

Non-compliant code

fun test(foo: Int): Int {
   if (foo > 0) {
      return 0
   } else {
      return 1
   }
}

(above code is for if used for returning value, the same can be applicable for variable assignment or when expression)

Compliant code

fun test(foo: Int): Int {
   return if (foo > 0) {
      0
   } else {
      1
   }
}

Context

Many times in my PR reviews in my work project I see these types of usages which generally happens with people who are new to Kotlin. Having this rule will not only improve the code as well as educated the usage of if and when as an expression

コントリビューターガイド