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

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

    Since you've tagged Scala, I'll give a Scala answer. Just use the existing Either class. Here's an example usage:

    def whatIsIt(flag: Boolean): Either[Int,String] = 
      if(flag) Left(123) else Right("hello")
    
    //and then later on...
    
    val x = whatIsIt(true)
    x match {
      case Left(i) => println("It was an int: " + i)
      case Right(s) => println("It was a string: " + s)
    }
    

    This is completely type-safe; you won't have problems with erasure or anything like that... And if you simply can't use Scala, at least use this as an example of how you can implement your own Either class.

提交回复
热议问题