Java 中的高级泛型 [英] Higher-kinded generics in 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 有 kind * -> * 而不是通常的 kind *.在 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()
这是无稽之谈.由于没有机制强制您仅使用通用 T
实例化 Foo
s,因此它拒绝编译.
which is nonsensical. Since there is no mechanism to force you to only instantiate Foo
s with generic T
s, it refuses to compile.
这篇关于Java 中的高级泛型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!