我正在为大型应用程序编写代码,并且有一个事件需要进行许多if / else检查。

例如:

if (i == 1) { /* some logic */ }
else if (i == 2) { /* some logic */ }
// ...
// ...
else if (i == 1000) { /* some logic */ }


有没有更有效或更有条理的方式来编写此代码?

最佳答案

听起来您有很多功能,只需要使用HashMapi将是地图的索引。哈希图非常有用,因为它们可以快速找到键的对应值,而无需比较大量值直到找到匹配项。

这是一个从HashMapAnyAny => Any的示例。因为Scala支持元组,所以这是一个完全通用的解决方案。

object Hello extends App {
  import scala.collection.immutable

  type F1 = (Any) => Any

  val hashMap: immutable.Map[Int, F1] =
    immutable.HashMap[Int, F1](
      1    -> { (a: Int)               => a * 2               }.asInstanceOf[F1], // Function literal that doubles it's input
      2    -> { (tuple: (String, Int)) => tuple._1 * tuple._2 }.asInstanceOf[F1], // Function literal that repeats the string
      1000 -> { (_: Unit)              => s"The date and time is ${ new java.util.Date() }" }.asInstanceOf[F1]
    )

  def lookup(i: Int, args: Any): Any = hashMap(i)(args)

  def report(i: Int, args: Any): Unit = println(s"$i: ${ lookup(i, args) }")

  report(1, 21)
  report(2, ("word ", 5))
  report(1000, ())
}


这是输出:

1: 42
2: word word word word word
1000: The date and time is Sat Dec 23 19:45:56 PST 2017


更新:这是使用数组的版本。请注意,此版本的索引必须从0开始,而不是以前的任意数字:

object Hello2 extends App {
  type F1 = (Any) => Any

  val array: Array[F1] =
    Array[F1](
      { (a: Int)               => a * 2               }.asInstanceOf[F1], // Function literal that doubles it's input
      { (tuple: (String, Int)) => tuple._1 * tuple._2 }.asInstanceOf[F1], // Function literal that repeats the string
      { (_: Unit)              => s"The date and time is ${ new java.util.Date() }" }.asInstanceOf[F1]
    )

  def lookup(i: Int, args: Any): Any = array(i)(args)

  def report(i: Int, args: Any): Unit = println(s"$i: ${ lookup(i, args) }")

  report(0, 21)
  report(1, ("word ", 5))
  report(2, ())
}


输出为:

0: 42
1: word word word word word
2: The date and time is Sat Dec 23 20:32:33 PST 2017

关于java - 努力编写高效的代码,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47957690/

10-11 22:29
查看更多