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

Unnamed Variables (_) can't be used in JShell

XMLWordPrintable

    • Icon: Bug Bug
    • Resolution: Fixed
    • Icon: P4 P4
    • 21
    • 21
    • tools
    • None
    • 21
    • b26
    • generic
    • generic

      When trying to use JEP 443: Unnamed Patterns and Variables (Preview) in JShell, I get the message that

      > as of release 21, the underscore keyword '_' is only allowed to declare
      > | unnamed patterns, local variables, exception parameters or lambda parameters

      Full reproducer:

      C:\Users\Johannes\dev\java>type Java21Test.java
      import java.lang.invoke.MethodHandles;

      public class Java21Test {
          public static void main(String[] args) throws Throwable {
              var _ = (String) MethodHandles.constant(String.class, "Hi").invokeExact();
          }
      }

      C:\Users\Johannes\dev\java>java --enable-preview --source 21 Java21Test.java
      Note: Java21Test.java uses preview features of Java SE 21.
      Note: Recompile with -Xlint:preview for details.

      C:\Users\Johannes\dev\java>jshell --enable-preview
      | Welcome to JShell -- Version 21-ea
      | For an introduction type: /help intro

      jshell> import java.lang.invoke.MethodHandles

      jshell> var _ = (String) MethodHandles.constant(String.class, "Hi").invokeExact();
      | Error:
      | as of release 21, the underscore keyword '_' is only allowed to declare
      | unnamed patterns, local variables, exception parameters or lambda parameters
      | var _ = (String) MethodHandles.constant(String.class, "Hi").invokeExact();
      | ^

      This error message is surprising, as to my knowledge `var` can only be used for local variables, therefore allowing the use of `_` as variable name as well.

            abimpoudis Angelos Bimpoudis
            jkuhn Johannes Kuhn
            Votes:
            0 Vote for this issue
            Watchers:
            4 Start watching this issue

              Created:
              Updated:
              Resolved: