代码之家  ›  专栏  ›  技术社区  ›  The Dog on the Log

Java中的规则切换和常规切换之间有什么区别?

  •  -2
  • The Dog on the Log  · 技术社区  · 2 年前

    我在其他地方找不到这个问题,所以我想我不妨问一下。这纯粹是美学吗?它在任何方面都更快吗?两者之间的主要区别是什么?我指的是定期切换

    switch(var){
        case 1:
            break;
    }
    

    我指的是规则转换

    switch(var){
        case 1 -> {}
    }
    
    1 回复  |  直到 2 年前
        1
  •  2
  •   queeg    2 年前

    在常规开关中,可以省略 break 代码块末尾的执行。这允许失败,并且您可以使用相同的代码处理几种不同的情况。

    switch(var) {
        case 1:
          dosomething();
          break;
        case 2:
          dosomethindelse();
                // the break was forgotten
        case 3:
        case 4: // these cases shall work on the same code
          doanotherthing();
                // but the break was forgotten
        default:
          donothing();
    }
    

    这个优点也是缺点,因为 打破 很容易被遗忘,然后导致难以发现的错误。

    因此引入了规则开关,根据其不同的语法,它不需要 打破 从而防止了这种情况的发生。

        2
  •  -1
  •   Cheng Thao    2 年前

    Java正在将函数式编程融入该语言中。第二个开关相当于Ocaml等函数语言中的模式匹配。

    下面是一个在Ocaml中计算列表中元素数量的示例。

    let mylist = [1;2;3;4;5;6];;
    
    let rec count lst = match lst with
      | [] -> 0
      | h::t-> 1 + (count t);;
    
    count mylist;;
    

    我们可以用Java 21实现类似的功能。

    static record Node (int value, Node next){};
      
    static int count(Node n){
       return switch(n){
          case null -> 0;
          case Node h-> 1 + count(h.next);
       };
    }
      
    public static void main(String[] args) {
      Node list = list = new Node(1, new Node(2, null));
      System.out.println(count(list));
    }