Creating a method which returns one or two parameters generically

前端 未结 2 367
遥遥无期
遥遥无期 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条回答
  • 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".

    0 讨论(0)
  • 2021-01-12 23:36

    Scala 2.13 introduced literal-based singleton types, so actually you can do a crazy thing like this:

    def foo(num: 10): (String, String) = ("Hello", "World")
    def foo(num: Int): String = s"Hello $num"
    
    val (left, right) = foo(10)
    val single = foo(2)
    

    and it will compile and work.

    Of course, you can return a list instead of a tuple for the 10 case if you wish.

    It should also work for typelevel scala (even before 2.13).

    With regular Lightbend Scala before 2.13 you could still do that, but it was a lot clunkier. It was necessary to use an additional trick involving using type called Witness, but fortunately, it is provided by shapeless:

    import shapeless.Witness
    import shapeless.syntax.singleton._
    
    def foo(num: Witness.`10`.T): (String, String) = ("Hello", "World")
    def foo(num: Int): String = s"Hello $num"
    
    val (left, right) = foo(10)
    val single = foo(2)
    

    And of course it is necessary to add shapeless as dependency:

    libraryDependencies += "com.chuusai" %% "shapeless" % "2.3.3"
    

    Another approach you could use is just the use of some kind of special container for your result. I would recommend tuple: (String, Option[String]). In case you're returning "regular" result, you would return (String, None) and in case of 10 you can return (String, Some[String]).

    0 讨论(0)
提交回复
热议问题