Wrapping chained method calls in Markdown file causes "illegal start of expression" error #2619
|
I am trying to use JBang's Markdown Script support, that is, I want to run all hello from Markdown
```java
"Hello World"
.chars()
.filter(Character::isUpperCase)
.forEach(c -> System.out.println("upper: " + (char) c));
```
more textHowever, trying to run this with JBang results in "illegal start of expression" errors: It seems the chained method calls which are wrapped to separate lines are causing compilation errors. |
Replies: 1 comment
|
(Answering my own question; mainly so that others who encounter the same problem find this solution.) By default JBang runs Java code in Markdown files using JDK's JShell, which executes the lines separately instead of recognizing it as a single statement wrapped across multiple lines. This can be worked around by adding an explicit Because JBang concatenates all code snippets in the file to one Java program and because most Markdown viewers support a subset of HTML, the <!--
```java
class Main {
public static void main(String... args) throws Exception {
```
-->
hello from Markdown
```java
"Hello World"
.chars()
.filter(Character::isUpperCase)
.forEach(c -> System.out.println("upper: " + (char) c));
```
more text
<!--
```java
}}
```
-->(The idea of using HTML comments is taken from the Endive documentation, which uses JBang to ensure that code snippets in the documentation compile.) |
(Answering my own question; mainly so that others who encounter the same problem find this solution.)
By default JBang runs Java code in Markdown files using JDK's JShell, which executes the lines separately instead of recognizing it as a single statement wrapped across multiple lines.
This can be worked around by adding an explicit
mainmethod (and using a recent JBang version which includes #2592, such as 0.141.0). JBang will then compile the code as regular Java code instead of as JShell snippet and wrapped statements are properly supported.Because JBang concatenates all code snippets in the file to one Java program and because most Markdown viewers support a subset of HTML, the
main…