命名条件if-value用于if块
为了限制双重代码实例的数量,我想在if语句中命名variables,就像在for循环中一样。
我的表情:
var hours = if (this.substringBefore(":").toInt() != 0) {this.substringBefore(":") + "h" } {else ""}
我想要的东西是:
var hours = if (MY_VAR = this.substringBefore(":").toInt() != 0) { MY_VAR + "h" } else { "" }
我主要是写在kotlin,但我很想find其他语言。
在Kotlin中,我建议使用高阶函数来创建这样一个临时variables,比如let
:
this.substringBefore(":").let { myval -> if (myval.toInt() != 0) { myval + "h" } else "" }