Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
964 views
in Technique[技术] by (71.8m points)

scala - Creating a method which returns one or two parameters generically

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 a situation where I need to call the same method, but with some parameter int value, I need to get in return 2 Strings, and not only one. My current way of implementing it is:

def foo(num: Int): List[String]

Where each time I call foo and get 1 String, I will get the head of the list, and each time I call for and it returns 2 strings, I will get the elements in [0, 1] (I know that when I call foo(10), I get 2 strings, and for the rest - only one).

Is there a more idiomatic scala/functional for this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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]).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...