Higher-kinded generics in Java(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中的高级泛型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java中的高级泛型
基础教程推荐
- 大摇大摆的枚举 2022-01-01
- Java Swing计时器未清除 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- 从 python 访问 JVM 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- 多个组件的复杂布局 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
