Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
300 views
in Technique[技术] by (71.8m points)

java - Implicit cast of functional interface

I want to implicitly cast my own interface implementation to a Java8 function.

My code:

import java.util.stream.Stream;

@FunctionalInterface
interface StringChanger {
    String change(String o);
}

public class A {

    public static void main(String[] args) {
        Stream.of("hello", "world")
                .map(new StringChanger() {

                    @Override
                    public String change(String o) {
                        return o.trim();
                    }
                })
                .forEach(System.out::println);
    }
}

Why does the cast not work?

I'm getting this exception:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
    The method map(Function<? super String,? extends R>) in the type Stream<String> is not applicable for the arguments (Trimmer)

    at A.main(A.java:13)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Well, the map method doesn't expect a StringChanger implementation. It expects a Function implementation.

What you can do is create an implementation of your StringChanger interface, and pass a method reference of your implementation to map :

 StringChanger sc = new StringChanger() {
     @Override
     public String change(String o) {
         return o.trim();
     }
 };
 Stream.of("hello", "world")
       .map(sc::change)
       .forEach(System.out::println);

EDIT:

In order to assign an implementation of one functional interface to a different functional interface reference, you can assign a method reference of the source functional interface's method :

    MyConsumer i3 = i::accept;
    IntConsumer i4 = i2::doSomething;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...