How can I simulate Haskell's “Either a b” in Java

后端 未结 14 2413
梦毁少年i
梦毁少年i 2020-12-07 22:40

How can I write a typesafe Java method that returns either something of class a or something of class b? For example:

public ... either(boolean b) {
  if (b)         


        
14条回答
  •  一个人的身影
    2020-12-07 23:28

    There is a stand-alone implementation of Either for Java 8 in a small library, "ambivalence": http://github.com/poetix/ambivalence

    It is closest to the Scala standard implementation - for example, it provides left and right projections for map and hashMap operations.

    There is no direct access to the left or right values; rather, you join the two types by providing lambdas to map them into a single result type:

    Either either1 = Either.ofLeft("foo");
    Either either2 = Either.ofRight(23);
    String result1 = either1.join(String::toUpperCase, Object::toString);
    String result2 = either2.join(String::toUpperCase, Object::toString);
    

    You can get it from Maven central:

    
        com.codepoetics
        ambivalence
        0.2
    
    

提交回复
热议问题