0 votes
1 view
in Java by (3.5k points)

I know how to create a reference to a method that has a String parameter and returns an int, it's:

Function<String, Integer>

However, this doesn't work if the function throws an exception, say it's defined as:

Integer myMethod(String s) throws IOException

How would I define this reference?

1 Answer

0 votes
by (46.1k points)

You can try any of the following.

  •  set your own functional interface that represents the checked exception:

@FunctionalInterface

public interface CheckedFunction<T, R> {

   R apply(T t) throws IOException;

}

and then use it:

void foo (CheckedFunction f) { ... }

  • Differently, wrap Integer myMethod(String s) in a manner that doesn't represent a checked exception:

public Integer myWrappedMethod(String s) {

    try {

        return myMethod(s);

    }

    catch(IOException e) {

        throw new UncheckedIOException(e);

    }

}

and then:

Function<String, Integer> f = (String t) -> myWrappedMethod(t);

or: 

Function<String, Integer> f =

    (String t) -> {

        try {

           return myMethod(t);

        }

        catch(IOException e) {

            throw new UncheckedIOException(e);

        }

    };

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Nov 12, 2019 in Java by Anvi (10.2k points)
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...