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中的高级泛型
基础教程推荐
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
