Java 中的多态值 [英] Polymorphic values in Java

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

问题描述

我正在学习 Haskell 并遇到了多态值.这些是根据上下文具有不同类型的值.例如,Nothing 的类型为 Maybe a[] 的类型为 [a].所以 [] 是你想要的任何东西的列表,你可以在任何需要任何列表的地方使用它.

I'm studying Haskell and came across polymorphic values. These are the values that have different type depending on the context. For example, Nothing has type Maybe a or [] has type [a]. So [] is list of anything you want and you can use it everywhere any list is expected.

我很难在 Java 中找到类似的东西,除了十亿美元的错误"null,它基本上属于任何类型.可能与无界通配符的泛型类似,但同样,我想不出一个例子.

I struggle to find a similar thing in Java, apart from "billion-dollar mistake" null, which is basically of any type. May be generics with unbounded wildcard is similar, but again, I can't think of an example.

Java 中有类似的东西吗?

Is there something similar in Java?

推荐答案

这与其说是实际答案,不如说是评论,但我需要更多空间.

This is more a comment than an actual answer, but I require more space.

虽然 Java 和 Haskell 的类型系统有很大的不同,但在某些特性中可以找到一些相似之处.这里有几个例子:请记住,下面显示的相关结构之间没有完美的对应关系.

While the type systems of Java and Haskell are quite apart, some similarities can be found in certain features. Here are a few examples: just keep in mind that there is no perfect correspondence between the related constructs shown below.

多态函数(如在 FP 中,而不是 OOP 多态):

Polymorphic functions (as in FP, not OOP polymorphism):

fst :: forall a b. (a, b) -> a
fst (x,y) = x

<A,B> A fst(A a, B b) {
    return a;
}

请注意,多态的非函数值不容易翻译.即使在 Haskell 中,诸如 3 :: Num a => 之类的值也是如此.a 是变相的函数.此外,[] :: [a]Nothing :: Maybe a 也被视为函数,在编译的某些阶段采用类型"参数——尽管,IIRC 在运行时这些参数消失了.

Note that polymorphic non-function values can not be translated as easily. Even in Haskell, values such as 3 :: Num a => a are functions in disguise. Further, [] :: [a] and Nothing :: Maybe a are also treated as functions, taking a "type" parameter in some stages of compilation -- albeit, IIRC at runtime these parameter disappear.

类型参数:

data T a = T a Int a

class T<A> {
    A x;
    int n;
    A y;

    T(A x, int n, A y) {
        this.x = x; this.n = n; this.y = y;
    }
}

代数数据类型(例如具有许多构造函数的 data):这些在 Java 中不直接可用.其他一些 JVM 语言,如 Scala,在语言中直接支持 ADT,以及模式修补和非穷尽性警告.在Java中,可以使用所谓的访问者模式来模拟ADT值消除,这是一个模式匹配的基本形式.

Algebraic data types (e.g. data with many constructors): these are not directly available in Java. Some other JVM languages, like Scala, have ADT supported directly in the language, as well as pattern patching and non-exhaustiveness warnings. In Java, you can use the so-called Visitor pattern to simulate ADT value elimination, which is a basic form of pattern matching.

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

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