How to reference a method with exception by using lambda expression

Introduction

This post would demo how to reference a method with exception by using lambda expression.

Environments

  • Java 1.8

1. Setup the environment

We have a Enum class Color that represents a color.

public enum Color {
    Red,Yellow;
}

2. Reference normal method as lambda expression

And we have a normal color convertor method here:

public Color getColor(String color) {
    return Color.valueOf(color);
}

It just consumes a color string and returns a Color object.

In order to use lambda expression to reference this method, we must use FunctionalInterface ,which is a special type of interface that contains only one abstract method.

We can use the java.util.function.Function to reference this type of method, it consumes something and returns another thing.

@FunctionalInterface public interface Function<T,R>

Represents a function that accepts one argument and produces a result.This is a functional interface whose functional method is apply(Object).

We define a method that accepts a FunctionalInterface like this:

public Color doFunction(Function<String,Color> function,String s) {
    return function.apply(s);
}

This method accepts a Function<String,Color> and a string, then apply this method on that string.

Then we can reference the getColor method as lambda expression like this:

Color color = doFunction((String s)->getColor(s),"Yellow");
System.out.println(color2);

3. Reference method with exception as lambda expression

But if we have a method that throws an exception like this:

public Color getColor(String color) throws Exception {
    return Color.valueOf(color);
}

The old code would not compile:

20180502_lambda_compile_failed

It’s because the java overriding mechanism, you can not throw more exception than the parent. And The java.util.function.Function interface doesn’t throw any exception, so you can not use it to reference a method with exception.

So, we can redefine a new @FunctionalInterface to solve this problem:

@FunctionalInterface
interface FunctionWithExceptionInterface<T,R> {
    R apply(T t) throws Exception;
}

And we change the doFunction method as well:

public Color doFunction(FunctionWithExceptionInterface<String,Color> function,String s) throws Exception {
    return function.apply(s);
}

The reference code is the same:

Color color = doFunction((String s)->getColor(s),"Yellow");
System.out.println(color2);

It compiles ok.

4. summary

In this post we demo the different situations of reference methods as lambda expression. If your method throws an exception, you can define a customized @FunctionalInterface to be compatible.

You can find detail documents about the java lambda here: