Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8300195

Fall-through issue occurs when using record pattern in switch statements

XMLWordPrintable

    • b32
    • generic
    • generic
    • Verified

        ADDITIONAL SYSTEM INFORMATION :
        Apple M1 Macbook Pro
        Mac OS Ventura 13.1
        Openjdk version "20-ea" 2023-03-21
        OpenJDK Runtime Environment (build 20-ea+31-2311)


        A DESCRIPTION OF THE PROBLEM :
        Fall-through issue occurs when trying to use record pattern with generic or non-generic types in switch statements

        STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
        I'm creating a record as follow:

        record Input<T>(T t){}

        Then I define a method called print that takes an Input<T> as parameter.

        private static <T> void print(Input<T> input){

                switch (input){
                    case Input(String s) -> System.out.println(s);
                    case Input(Double i) -> System.out.println(i);
                    default -> System.out.println("defult");
                }
            }

        Then I create two Input instances of different types

        var stringInput = new Input<>("String");
        var intInput = new Input<>(1.2);

        Finally I pass two different types of input instances as arguments to the print method.

        print(stringInput);
        print(intInput);

        EXPECTED VERSUS ACTUAL BEHAVIOR :
        EXPECTED -
        Waiting to see Hello and 1.2 results in console
        ACTUAL -
        I'm getting java.lang.ClassCastException that says "class java.lang.String cannot be cast to class java.lang.Double (java.lang.String and java.lang.Double are in module java.base of loader 'bootstrap')

        ---------- BEGIN SOURCE ----------
        public class FallThroughIssueExample
        {

            public static void main(String[] args) {

                var stringInput = new Input<>("Hello");
                var intInput = new Input<>(1.2);

                print(stringInput);
                print(intInput);
            }

            private static <T> void print(Input<T> input){

                switch (input){
                    case Input(String s) -> System.out.println(s);
                    case Input(Double i) -> System.out.println(i);
                    default -> System.out.println("defult");
                }
            }
        }

        record Input<T>(T t){}
        ---------- END SOURCE ----------

        FREQUENCY : always


              jlahoda Jan Lahoda
              webbuggrp Webbug Group
              Votes:
              0 Vote for this issue
              Watchers:
              5 Start watching this issue

                Created:
                Updated:
                Resolved: