Home > Enterprise >  What is the concise way to write following code segment in Kotlin
What is the concise way to write following code segment in Kotlin

Time:05-23

I am learning Kotlin and I have written following code snippets in Kotlin. Rather than using if-else condition is there any concise way to write following code?

fun(a: int, b: int): String {
   Coding().apply{
    if(a>b){
     comment = "first value grater than second value"
     value = a
    }else{
     comment = "second value grater than or equal to first value"
     value = b
    }  
   }
}

CodePudding user response:

comment = if (a > b) "first value grater than second value" else "second value grater than or equal to first value"
value = max(a, b)

CodePudding user response:

You can replace with a when expression as below;

   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
            }
      }

But as per docs also, if the condition is a simple binary condition, use if statements. If you have to handle more than three conditions, prefer when. More info https://kotlinlang.org/docs/coding-conventions.html#if-versus-when

  • Related