Ankita Bhowmik
Ankita Bhowmik

Reputation: 463

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.

Upvotes: 6

Views: 2276

Answers (2)

Malinda
Malinda

Reputation: 366

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>

Upvotes: 1

Tunaki
Tunaki

Reputation: 137309

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>

Upvotes: 6

Related Questions