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

后端 未结 14 2359
梦毁少年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:32

    The suggestions already provided, although feasible, are not complete as they rely on some null references and effectively make "Either" masquerade as a tuple of values. A disjoint sum is obviously one type or the other.

    I'd suggest having a look at the implementation of FunctionalJava's Either as an example.

提交回复
热议问题