Home > Software design >  TS shorten code with repetition in if expression
TS shorten code with repetition in if expression

Time:11-01

I want to shorten my code that currently looks like this:

                onClick={value => {
            
              if (value === "valA") {
                Mutation.mutate({filter, source: "sourceA" }, {someRepetitiveCode}}, 
              } else if (value === "valB") {
                Mutation.mutate({filter, source: "sourceB" }, {someRepetitiveCode}}, 
             else {
                Mutation.mutate({filter, source: undefined },{someRepetitiveCode}} 
                
            }

There is a lot of repetition in the code so I wanted to ask if there is a way to shorten that expression e.g. with a lambda expression.

CodePudding user response:

Not entirely sure what you want but it looks to me that you want to assign something to source depending on the value. I think this is what you maybe are looking for:

source = when(value) {
    "valA" -> "sourceA"
    "valB" -> "sourceB"
    else -> "undefined"
}

CodePudding user response:

There is no ternary operator in kotlin, you can't use ?: known from other languages like java or c . It is replaced with if which can be used as expression, or when, see example below:

fun some_func( lmbd: (String) -> Boolean ) {
    if (lmbd("text"))
        println("lmbd is true")
}

fun main(args: Array<String>) {
    some_func({param1 -> if (param1 == "text") true else false})
    some_func({param1 -> 
        when (param1) {
        "text1",
        "text" -> true;
        else -> false;}}
     )
}
  • Related