简体   繁体   中英

Error in compilation of code with lambda expression

I have the following code:

package com.mongoDB;

import spark.Spark;

public class HelloWorldSparkStyle {
   public static void main(String[] args) {
       Spark.get("/hello", (req, res) -> "Hello World");
   }
}

It runs fine when I run it through main method but throws the following error when I try to compile it:

\HelloWorldSparkStyle.java:[9,33] error: lambda expressions are not supported in -source 1.5

D:\WorkspaceWithJava8\BeginnerProject>javac -version
javac 1.8.0_60

I am using Eclipse IDE and trying to compile it through command line.

By default, the maven-compiler-plugin uses Java 5 to compile the classes. Quoting its documentation :

Also note that at present the default source setting is 1.5 and the default target setting is 1.5, independently of the JDK you run Maven with. If you want to change these defaults, you should set source and target as described in Setting the -source and -target of the Java Compiler.

You need to configure it to use Java 8, like this:

<plugin>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.3</version>
    <configuration>
      <source>1.8</source>
      <target>1.8</target>
    </configuration>
</plugin>

Let me elaborate above answer further. Put the plugin given in above answer between <project> and </project> as below.

<build>
<plugins>
    <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.3</version>
        <configuration>
            <source>1.8</source>
            <target>1.8</target>
        </configuration>
    </plugin>
</plugins>
</build>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM