Is there a way to use method references for top-level functions in jshell?

Viewed 777

Suppose I do this in jshell:

jshell> void printIsEven(int i) {
   ...>     System.out.println(i % 2 == 0);
   ...> }
|  created method printIsEven(int)

jshell> List<Integer> l = Arrays.asList(7,5,4,8,5,9);
l ==> [7, 5, 4, 8, 5, 9]

jshell> l.forEach(/* ??? */); // is it possible to use a method reference here?

In a normal program I could write l.forEach(this::printIsEven) in a non-static context or l.forEach(MyClass::printIsEven) in the static context of a class named MyClass.

Using this::printIsEven in jshell doesn't work because jshell executes statements in a static context, but you can't use a static method reference because there's no class name to prefix ::printIsEven, and trying l.forEach(::printIsEven) is just a syntax error.

2 Answers

Being thoroughly aware of a risk stating an obvious thing, there's an easier way to refer to top-level function declaration, compared to wrapping them in classes.

jshell> void printIsEven(int i) {
...>     System.out.println(i % 2 == 0);
...> }
|  created method printIsEven(int)

jshell> List<Integer> l = Arrays.asList(7,5,4,8,5,9);
l ==> [7, 5, 4, 8, 5, 9]

jshell> l.forEach(i -> printIsEven(i)); // lambdas can refer to top-level declarations

It's not what's been asked, but it's just a handy way to use e.g. streams APIs.

Related