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

suspected bug with respect to generic method type inference

XMLWordPrintable

    • generic
    • generic

      ADDITIONAL SYSTEM INFORMATION :
      macOS Monterey, 12.3.1

      A DESCRIPTION OF THE PROBLEM :
      when calling a static method foo(..) parameterized by a type parameter U, if the method foo takes two formal parameters of generic type U, one can call foo("2", 1);

      I was under the impression one of the main reasons for adding generic types was to preclude behavior like this?

      REGRESSION : Last worked in version 8

      STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
      Here is a minimal example:
          public static <U> U foo(U x, U y) {
              return y != null ? y : x;
          }

          public static void main(String[] args) {
              Integer a = 1;
              String b = "x";
              foo(a, b); //<-- U first gets instantiated by Integer, but then a String is supplied.
          }


      EXPECTED VERSUS ACTUAL BEHAVIOR :
      EXPECTED -
      Shouldn't the call to foo(..) in main represent a compile time bug caught by the typechecker? Shouldn't both arguments to foo be required to be the same type (since both parameters were given U as their type)?
      ACTUAL -
      program compiles fine and without issue. It's only when one does this:
      Integer m = foo(a, b);

      does the typechecker pick it up as an issue. But if foo(..) returned a boolean or void, then the code would compile just fine and the bug might go unseen.

      Instantiating the type parameter manually makes the typechecker catch it: Integer m = Main.<Integer>foo(a, b);

      ---------- BEGIN SOURCE ----------
      see steps to reproduce
      ---------- END SOURCE ----------

      FREQUENCY : rarely


            adev Anupam Dev
            webbuggrp Webbug Group
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

              Created:
              Updated:
              Resolved: