简体   繁体   中英

Polymorphic values in Java

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.

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.

Is there something similar in Java?

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

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.

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;
}

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.

Type arguments:

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;
    }
}

Algebraic data types (eg 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.

A polymorphic value like [] can only be represented as a method in Java. In fact, this method already exists in the Arrays class and is called asList . And because of Java's type inference, you don't even need to provide type arguments:

import java.util.Arrays;
import java.util.List;

public class Test {
    public static void main(String[] args) {
        List<String> myList = Arrays.asList();
    }
}

If you ignore all the noise, []Arrays.asList() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM