Java中的高级泛型 [英] Higher-kinded generics in Java

查看:16
本文介绍了Java中的高级泛型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下课程:

public class FixExpr {
  Expr<FixExpr> in;
}

现在我想介绍一个通用参数,对 Expr 的使用进行抽象:

Now I want to introduce a generic argument, abstracting over the use of Expr:

public class Fix<F> {
  F<Fix<F>> in;
}

但 Eclipse 不喜欢这样:

But Eclipse doesn't like this:

类型 F 不是泛型的;它不能用参数 <Fix<F>>

The type F is not generic; it cannot be parametrized with arguments <Fix<F>>

这是否可能,或者我是否忽略了导致此特定实例中断的某些内容?

Is this possible at all or have I overlooked something that causes this specific instance to break?

一些背景信息:在 Haskell 中,这是编写泛型函数的常用方法;我正在尝试将其移植到 Java.上例中的类型参数 F 具有种类 * -> * 而不是通常的种类 *.在 Haskell 中它看起来像这样:

Some background information: in Haskell this is a common way to write generic functions; I'm trying to port this to Java. The type argument F in the example above has kind * -> * instead of the usual kind *. In Haskell it looks like this:

newtype Fix f = In { out :: f (Fix f) }

推荐答案

我认为 Java 泛型根本不支持您尝试做的事情.更简单的情况

I think what you're trying to do is simply not supported by Java generics. The simpler case of

public class Foo<T> {
    public T<String> bar() { return null; }
}

也不使用 javac 编译.

also does not compile using javac.

由于Java 在编译时不知道T 是什么,它不能保证T 是有意义的.例如,如果您创建了一个 Foo,则 bar 将具有签名

Since Java does not know at compile-time what T is, it can't guarantee that T<String> is at all meaningful. For example if you created a Foo<BufferedImage>, bar would have the signature

public BufferedImage<String> bar()

这是荒谬的.由于没有机制强制你只用通用 Ts 实例化 Foos,它拒绝编译.

which is nonsensical. Since there is no mechanism to force you to only instantiate Foos with generic Ts, it refuses to compile.

这篇关于Java中的高级泛型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆