improve if condition with scala

时间:2019-04-08 13:49:48

标签: scala

I wrote this:

if (fork == "0" || fork == "1" || fork == "3" || fork == "null"  ) {
 list2 :: List(
    Wrapper(
      Location.PL_TYPES,
      subType,
      daFuncId,
      NA,
      name,
      code)
  )
}
else list2  :: List(
  Wrapper(
    Location.PL_TYPES,
    subType,
    NA,
    NA,
    name,
    code
  )
)

}

I want to improve this by replacing the if else with another pattern

best regards

4 个答案:

答案 0 :(得分:6)

It seems only the ID is different between the two cases. You could use pattern matching to choose the id, and append to the list only after so you don't repeat the Wrapper construction:

val id = fork match {
  case "0" | "1" | "3" | "null" => daFuncId
  case _ => NA
}

list2 :: List(
  Wrapper(
    Location.PL_TYPES,
    subType,
    id,
    NA,
    name,
    code)
)

答案 1 :(得分:0)

You can write the same if-else condition using pattern matching in scala.

fork match {
  case "0" | "1" | "3" | null =>
    list2 :: List(
      Wrapper(
        Location.PL_TYPES,
        subType,
        daFuncId,
        NA,
        name,
        code)
    )
  case _ =>
    list2  :: List(
      Wrapper(
        Location.PL_TYPES,
        subType,
        NA,
        NA,
        name,
        code
      )
    )
}

Please let me know if this works out for you.

答案 2 :(得分:0)

 list2 :: List(fork)
  .map {
     case "0" | "1" | "3" | "null" => daFuncId
     case _ => NA
  }.map { id => 
    Wrapper(Location.PL_TYPES, subType, id, NA, name, code)
  }

答案 3 :(得分:0)

不是特定于Scala的,但我建议这样:

if (List("0", "1", "3", "null").contains(fork)) {

} else {

}