我正在學習 Kotlin,并且我在 Kotlin 中撰寫了以下代碼片段。除了使用 if-else 條件之外,還有什么簡潔的方法可以撰寫以下代碼?
fun test(a: int, b: int): Coding {
return Coding().apply{
if(a>b){
comment = "first value greater than second value"
value = a
}else{
comment = "second value greater than or equal to first value"
value = b
}
}
}
uj5u.com熱心網友回復:
comment = if (a > b) "first value grater than second value" else "second value grater than or equal to first value"
value = max(a, b)
uj5u.com熱心網友回復:
您可以用when如下運算式替換;
when {
a > b -> {
comment = "first value grater than second value"
value = a
}
else -> {
comment = "second value grater than or equal to first value"
value = b
}
}
但也根據檔案,如果條件是簡單的二進制條件,請使用if陳述句。如果您必須處理三個以上的條件,則首選when. 更多資訊https://kotlinlang.org/docs/coding-conventions.html#if-versus-when
uj5u.com熱心網友回復:
作為帶有 if 運算式的 Kotlin 單行代碼:
val a = 5
val b = 9
val (value, comment) = if (a > b) Pair(a, "first value greater than second value") else Pair(b, "second value greater than or equal to first value")
Pair 表示兩個值的通用對。
uj5u.com熱心網友回復:
基于@Laksitha 和@Twistleton 回答了這兩個建議的組合:
val (value, comment) = when {
a > b -> a to "first value greater than second value"
else -> b to "second value greater than or equal to first value"
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/480447.html
