Creating a method which returns one or two parameters generically

前端 未结 2 392
遥遥无期
遥遥无期 2021-01-12 22:55

I have a method

def foo(num: Int): String

Where I call some in some places in my code, and everything was good.
Lately, I encountered

2条回答
  •  猫巷女王i
    2021-01-12 23:15

    Since the result space is cleanly split into two sides (disjointed) consider Either like so

    def foo(i: Int): Either[(String, String), String] =
      if (i == 10) Left("one", "two") else Right("one")
    
    val Left(Tuple2(x, y)) = foo(10)
    val Right(a) = foo(2)
    

    which is inspired by @Krzysztof's edit regarding "special container".

提交回复
热议问题