创建一个通常返回一个或两个参数的方法 [英] Creating a method which returns one or two parameters generically
问题描述
我有一种方法
def foo(num: Int): String
我在代码中的某些位置进行了调用,一切都很好.
最近,我遇到一种情况,我需要调用相同方法,但是由于具有一些参数int值,我需要获取返回的 2个字符串,而不仅仅是一个.我目前的实现方式是:
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]
每次调用foo
并获得 1 字符串时,我都将成为列表的头,并且每次调用并返回2个字符串时,我都将得到其中的元素[0,1](我知道当我调用foo(10)
时,我得到2个字符串,其余的-只有一个).
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).
是否有更多惯用的scala/功能?
Is there a more idiomatic scala/functional for this?
推荐答案
Scala 2.13 引入了基于文字的单例类型,因此实际上您可以做这样的疯狂事情:
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)
,它将编译并运行.
当然,您可以根据需要返回列表,而不是 10 的元组.
Of course, you can return a list instead of a tuple for the 10 case if you wish.
它也应该适用于 typelevel scala (甚至在 2.13 之前).
It should also work for typelevel scala (even before 2.13).
在 2.13 之前使用常规的 Lightbend Scala ,您仍然可以做到这一点,但这要笨拙得多.有必要使用一个额外的技巧,涉及使用称为 Witness 的类型,但幸运的是,它是由 shapeless
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)
当然,有必要添加 shapeless 作为依赖项:
And of course it is necessary to add shapeless as dependency:
libraryDependencies += "com.chuusai" %% "shapeless" % "2.3.3"
您可以使用的另一种方法是使用某种特殊的容器来获得结果.我会推荐元组:(String, Option[String])
.如果返回的是常规"结果,则返回(String, None)
;如果返回的是 10 ,则可以返回(String, Some[String])
.
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])
.
这篇关于创建一个通常返回一个或两个参数的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!