Scala API 中的选项和命名默认参数是油和水吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4199393/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Are Options and named default arguments like oil and water in a Scala API?
提问by DaGGeRRz
I'm working on a Scala API (for Twilio, by the way) where operations have a pretty large amount of parameters and many of these have sensible default values. To reduce typing and increase usability, I've decided to use case classes with named and default arguments. For instance for the TwiML Gather verb:
我正在研究 Scala API(顺便说一下,对于 Twilio),其中的操作具有大量参数,并且其中许多具有合理的默认值。为了减少输入并提高可用性,我决定使用带有命名和默认参数的案例类。例如对于 TwiML Gather 动词:
case class Gather(finishOnKey: Char = '#',
numDigits: Int = Integer.MAX_VALUE, // Infinite
callbackUrl: Option[String] = None,
timeout: Int = 5
) extends Verb
The parameter of interest here is callbackUrl. It is the only parameter which is reallyoptional in the sense that if no value is supplied, no value will be applied (which is perfectly legal).
这里感兴趣的参数是callbackUrl。它是唯一一个真正可选的参数,如果没有提供任何值,则不会应用任何值(这是完全合法的)。
I've declared it as an option in order to do the monadic map routine with it on the implementation side of the API, but this puts some extra burden on the API user:
我已经将它声明为一个选项,以便在 API 的实现端使用它来执行 monadic 映射例程,但这给 API 用户带来了一些额外的负担:
Gather(numDigits = 4, callbackUrl = Some("http://xxx"))
// Should have been
Gather(numDigits = 4, callbackUrl = "http://xxx")
// Without the optional url, both cases are similar
Gather(numDigits = 4)
As far as I can make out, there are two options (no pun intended) to resolve this. Either make the API client import an implicit conversion into scope:
据我所知,有两种选择(不是双关语)来解决这个问题。要么让 API 客户端将隐式转换导入范围:
implicit def string2Option(s: String) : Option[String] = Some(s)
Or I can redeclare the case class with a null default and convert it to an option on the implementation side:
或者我可以使用 null 默认值重新声明 case 类并将其转换为实现端的选项:
case class Gather(finishOnKey: Char = '#',
numDigits: Int = Integer.MAX_VALUE,
callbackUrl: String = null,
timeout: Int = 5
) extends Verb
My questions are as follows:
我的问题如下:
- Are there any more elegant ways to solve my particular case?
- More generally: Named arguments is a new language feature (2.8). Could it turn out that Options and named default arguments are like oil and water? :)
- Might using a null default value be the best choice in this case?
- 有没有更优雅的方法来解决我的特殊情况?
- 更一般地说:命名参数是一个新的语言特性 (2.8)。难道选项和命名的默认参数就像油和水一样吗?:)
- 在这种情况下,使用空默认值可能是最佳选择吗?
采纳答案by Aaron Novstrup
Here's another solution, partly inspired by Chris' answer. It also involves a wrapper, but the wrapper is transparent, you only have to define it once, and the user of the API doesn't need to import any conversions:
这是另一个解决方案,部分灵感来自Chris 的回答。它还涉及到一个包装器,但包装器是透明的,你只需要定义一次,API的用户不需要导入任何转换:
class Opt[T] private (val option: Option[T])
object Opt {
implicit def any2opt[T](t: T): Opt[T] = new Opt(Option(t)) // NOT Some(t)
implicit def option2opt[T](o: Option[T]): Opt[T] = new Opt(o)
implicit def opt2option[T](o: Opt[T]): Option[T] = o.option
}
case class Gather(finishOnKey: Char = '#',
numDigits: Opt[Int] = None, // Infinite
callbackUrl: Opt[String] = None,
timeout: Int = 5
) extends Verb
// this works with no import
Gather(numDigits = 4, callbackUrl = "http://xxx")
// this works too
Gather(numDigits = 4, callbackUrl = Some("http://xxx"))
// you can even safely pass the return value of an unsafe Java method
Gather(callbackUrl = maybeNullString())
To address the larger design issue, I don't think that the interaction between Options and named default parameters is as much oil-and-water as it might seem at first glance. There's a definite distinction between an optional field and one with a default value. An optional field (i.e. one of type Option[T]) might neverhave a value. A field with a default value, on the other hand, simply does not require its value to be supplied as an argument to the constructor. These two notions are thus orthogonal, and it's no surprise that a field may be optional and have a default value.
为了解决更大的设计问题,我认为 Options 和命名默认参数之间的交互并不像乍一看那样像油水一样。可选字段和具有默认值的字段之间有明确的区别。可选字段(即 type 之一Option[T])可能永远不会有值。另一方面,具有默认值的字段不需要将其值作为参数提供给构造函数。因此,这两个概念是正交的,字段可能是可选的并具有默认值也就不足为奇了。
That said, I think a reasonable argument can be made for using Optrather than Optionfor such fields, beyond just saving the client some typing. Doing so makes the API more flexible, in the sense that you can replace a Targument with an Opt[T]argument (or vice-versa) without breaking callers of the constructor[1].
也就是说,我认为可以为使用Opt而不是Option为此类字段提出合理的论据,而不仅仅是为客户端节省一些输入。这样做会使 API 更加灵活,因为您可以用T参数替换Opt[T]参数(反之亦然),而不会破坏构造函数的调用者 [1]。
As for using a nulldefault value for a public field, I think this is a bad idea. "You" may know that you expect a null, but clients that access the field may not. Even if the field is private, using a nullis asking for trouble down the road when other developers have to maintain your code. All the usual arguments about nullvalues come into play here -- I don't think this use case is any special exception.
至于为null公共字段使用默认值,我认为这是一个坏主意。“您”可能知道您需要一个null,但访问该字段的客户端可能不会。即使该字段是私有的,null当其他开发人员必须维护您的代码时,使用 a也会带来麻烦。所有关于null值的常见论点都在这里发挥作用——我不认为这个用例是任何特殊的例外。
[1] Provided that you remove the option2opt conversion so that callers must pass a Twhenever an Opt[T]is required.
[1] 前提是您删除了 option2opt 转换,以便调用者必须T在Opt[T]需要时传递 a 。
回答by oxbow_lakes
Don't auto-convert anything to an Option. Using my answer here, I think you can do this nicely but in a typesafe way.
不要将任何内容自动转换为选项。在这里使用我的回答,我认为您可以很好地但以类型安全的方式做到这一点。
sealed trait NumDigits { /* behaviour interface */ }
sealed trait FallbackUrl { /* behaviour interface */ }
case object NoNumDigits extends NumDigits { /* behaviour impl */ }
case object NofallbackUrl extends FallbackUrl { /* behaviour impl */ }
implicit def int2numd(i : Int) = new NumDigits { /* behaviour impl */ }
implicit def str2fallback(s : String) = new FallbackUrl { /* behaviour impl */ }
class Gather(finishOnKey: Char = '#',
numDigits: NumDigits = NoNumDigits, // Infinite
fallbackUrl: FallbackUrl = NoFallbackUrl,
timeout: Int = 5
Then you can call it as you wanted to - obviously adding your behaviourmethods to FallbackUrland NumDigitsas appropriate. The main negative here is that it is a ton of boilerplate
然后你可以随意调用它 - 显然,在适当的时候添加你的行为方法。这里的主要缺点是它是大量的样板文件FallbackUrlNumDigits
Gather(numDigits = 4, fallbackUrl = "http://wibble.org")
回答by IttayD
Personally, I think using 'null' as default value is perfectly OK here. Using Option instead of null is when you want to convey to your clients that something may not be defined. So a return value may be declared Option[...], or a method arguments for abstract methods. This saves the client from reading documentation or, more likely, get NPEs because of not realizing something may be null.
就个人而言,我认为在这里使用 'null' 作为默认值是完全可以的。使用 Option 而不是 null 是当您想向客户传达可能未定义某些内容时。因此,返回值可以声明为 Option[...],或者是抽象方法的方法参数。这可以避免客户端阅读文档,或者更有可能因为没有意识到某些内容可能为空而获得 NPE。
In your case, you are aware that a null may be there. And if you like Option's methods just do val optionalFallbackUrl = Option(fallbackUrl)at the start of the method.
在您的情况下,您知道可能存在空值。如果您喜欢 Option 的方法,只需val optionalFallbackUrl = Option(fallbackUrl)在方法的开头执行即可。
However, this approach only works for types of AnyRef. If you want to use the same technique for any kind of argument (without resulting to Integer.MAX_VALUE as replacement for null), then I guess you should go with one of the other answers
但是,这种方法仅适用于 AnyRef 类型。如果您想对任何类型的参数使用相同的技术(不会导致 Integer.MAX_VALUE 替换为 null),那么我想您应该使用其他答案之一
回答by Debilski
I think as long as no language support in Scala for a real kind of void (explanation below) ‘type', using Optionis probably the cleaner solution in the long run. Maybe even for all default parameters.
我认为只要 Scala 中没有语言支持真正的 void(解释如下)“类型”,Option从长远来看,使用可能是更清晰的解决方案。甚至可能适用于所有默认参数。
The problem is, that people who use your API know that some of your arguments are defaulted might as well handle them as optional. So, they're declaring them as
问题是,使用你的 API 的人知道你的一些参数是默认的,也可以将它们作为可选来处理。所以,他们宣布他们为
var url: Option[String] = None
It's all nice and clean and they can just wait and see if they ever get any information to fill this Option.
这一切都很好而且很干净,他们可以等待,看看他们是否能得到任何信息来填写这个选项。
When finally calling your API with a defaulted argument, they'll face a problem.
当最终使用默认参数调用您的 API 时,他们将面临问题。
// Your API
case class Gather(url: String) { def this() = { ... } ... }
// Their code
val gather = url match {
case Some(u) => Gather(u)
case _ => Gather()
}
I think it would be much easier then to do this
我认为这样做会容易得多
val gather = Gather(url.openOrVoid)
where the *openOrVoidwould just be left out in case of None. But this is not possible.
其中,*openOrVoid将刚刚在的情况下,被排除在外None。但这是不可能的。
So you really should think about who is going to use your API and how they are likely to use it. It may well be that your users already use Optionto store all variables for the very reason that they know they are optional in the end…
所以你真的应该考虑谁将使用你的 API 以及他们可能如何使用它。很可能您的用户已经使用Option存储所有变量,因为他们知道它们最终是可选的……
Defaulted parameters are nice but they also complicate things; especially when there is already an Optiontype around. I think there is some truth in your second question.
默认参数很好,但它们也使事情复杂化;特别是当Option周围已经有一个类型时。我认为你的第二个问题有一些道理。
回答by Daniel C. Sobral
I think you should bite the bullet and go ahead with Option. I have faced this problem before, and it usually went away after some refactoring. Sometimes it didn't, and I lived with it. But the factis that a default parameter is not an "optional" parameter -- it's just one that has a default value.
我认为你应该咬紧牙关继续前进Option。我以前遇到过这个问题,通常经过一些重构后它就会消失。有时它没有,我忍受它。但事实是,默认参数不是“可选”参数——它只是具有默认值的参数。
I'm pretty much in favor of Debilski'sanswer.
我非常赞成Debilski 的回答。
回答by pr1001
Might I just argue in favor of your existing approach, Some("callbackUrl")? It's all of 6 more characters for the API user to type, shows them that the parameter is optional, and presumably makes the implementation easier for you.
我可以争论支持您现有的方法Some("callbackUrl")吗?API 用户可以输入 6 个以上的字符,向他们表明该参数是可选的,并且可能使您的实现更容易。
回答by Ben Hymanson
I was also surprised by this. Why not generalize to:
我也对此感到惊讶。为什么不概括为:
implicit def any2Option[T](x: T): Option[T] = Some(x)
Any reason why that couldn't just be part of Predef?
有什么理由不能只是 Predef 的一部分?

