Java中更高级的泛型 [英] Higher-kinded generics in Java
问题描述
假设我有以下类:
public class FixExpr {
Expr< FixExpr>在;
}
现在我想介绍一个通用的参数,抽象使用Expr:
public class Fix< F> {
F<修复< F>>在;
}
但Eclipse不喜欢这样:
类型F不是通用的;它不能用参数参数化< Fix< F>>
这是可能的,还是我忽略了导致这种情况的原因有些背景信息:在Haskell中,这是编写泛型函数的常用方法;在Haskell中,我正试图将其移植到Java。上例中的类型参数F具有* - > *类型,而不是通常的类型*。在Haskell中,它看起来像这样:
newtype修复f = In {out :: f(Fix f)}
我认为你所要做的只是Java不支持仿制药。
public class Foo< T> {
public T< String> bar(){return null; }
}
也不使用javac编译。
由于Java在编译时并不知道 T
是什么,它不能保证 T
完全有意义。例如,如果您创建了 Foo< BufferedImage>
,那么 bar
将具有签名
public BufferedImage< String> bar()
这是无意义的。由于没有任何机制迫使你只用 T
s实例化 Foo
s,所以它拒绝编译。 / p>
Suppose I have the following class:
public class FixExpr {
Expr<FixExpr> in;
}
Now I want to introduce a generic argument, abstracting over the use of Expr:
public class Fix<F> {
F<Fix<F>> in;
}
But Eclipse doesn't like this:
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?
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) }
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; }
}
also does not compile using javac.
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()
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屋!