0

I am an absolute Java newbie and just got started learning Java. I came across this JShell functionality within IntelliJ where one can write some quick code without writing any class constructs. But the problem which annoys me for quite some time is that when I initialized even a simple ArrayList, it seems to be working fine but it always gives me this "Expression expected" error which underlines List<Integer> in red.

I do not encounter such error while in a normal .java file but only in JShell.

Does anyone know why? Much appreciated in advance!

enter image description here

codeedoc
  • 454
  • 2
  • 7
  • 16
  • 1
    I cannot reproduce that error using `jshell` directly (not though IDEA) - have you tried using `jshell` outside the IDE? – user16320675 Mar 07 '22 at 22:08
  • @user16320675 yeah I just tried using it in the terminal. It worked fine as expected. So I guess the problem boils down to why IntelliJ complains about "Expression expected" but nonetheless was able to run the code. – codeedoc Mar 07 '22 at 22:16

1 Answers1

3

This is an IntelliJ bug, and has been reported in IDEA-221953 and IDEA-191768 for example. The editor doesn't seem to understand generics (among other things like var) when they appear in code snippets.

Note that this isn't the case if you write the statement inside a method,

static void foo() {
    List<Integer> foo = new ArrayList<>();
    // ...
}
foo();

but of course, that sort of defeats the purpose of using JShell :(

Running the code itself isn't affected. You can still run the code by pressing cmd/ctrl + enter, and it will work as you expect, despite all the red squiggles.

Sweeper
  • 213,210
  • 22
  • 193
  • 313