java implement 泛型,在Java 8中返回泛型函数接口

I want to write kind of function factory. It should be a function, which is called once which different strategies as parameters. It should return a function, which selects one of this strategies dependent on the parameter, which is to be fulfilled by a predicate.

Well, better look at condition3 for better understanding.

The problem is, that it is not compiling. I think because the compiler can't figure out, that the functional interface H can be realized by the implementation.

Without generics it is working fine.

@FunctionalInterface

public interface Finder {

Stream findBest (T t);

// Valid code

static

Finder

condition1 () {

return p -> null;

}

// Valid code, but selects just one of the H's when the method is invoked

static

> H condition2 (Pair, H>... hs) {

return hs[0].getRight ();

}

// Should return a method, which selects the appropiate H

// whenever it is invoked with an P

// Compiler complain:

// The target type of this expression must be a functional interface

static

> H condition3 (Pair, H>... hs) {

return p -> stream (hs).filter (pair -> pair.getLeft ().test (p))

.findFirst ()

.map (Pair::getRight)

.map (h -> h.findBest (p))

.orElseGet (Stream::empty);

}

}

So what's the problem here? Can I solve it and if it's possible with Java: how?

解决方案

Look at the signature of your method and try to tell what the exact return type is:

static

> H condition3(…

Lambdas can only implement an interface known at compile-time. But the actual type argument for H is not known to the compiler.

Your first method works because it returns the type Finder

which the lambda can implement, your second works because it doesn’t use a lambda for implementing the return type H extends Finder

.

Only your third method attempts to specify a lambda expression for a type argument H extends Finder

.

A solution is not to give the caller the freedom to mandate a particular sub-type of Finder as the method’s return type:

static

>

Finder

condition3(Pair, H>... hs) {

To illustrate what implications your original method signature has, look at the following example:

final class HImpl implements Finder {

public Stream findBest(String t) {

return null; // just for illustration, we never really use the class

}

}

HImpl x=Finder.condition3();

Given your original method signature this compiles without any error. But how ought the method condition3 provide an instance of HImpl here using your lambda expression?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值