隐式参数VS默认参数值 [英] implicit parameter VS default parameter value

查看:72
本文介绍了隐式参数VS默认参数值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Scala中至少有两种技术可以将默认值传递给方法

There are, at least, two techniques in Scala to pass default value to a method

1)默认参数值

scala> def f(i: Int = 0) = i
f: (i: Int)Int

scala> f()
res0: Int = 0

scala> f(1)
res1: Int = 1

2)隐式参数

scala> def g(implicit i: Int) = i
g: (implicit i: Int)Int

scala> implicit val default = 0
default: Int = 0

scala> g(1)
res5: Int = 1

scala> g
res7: Int = 0

在哪种情况下,您选择一个还是另一个? 借助隐式功能,默认值是有用的功能吗?

In which case do you choose one or another ? With the power of implicit, default values are they a usefull feature ?

推荐答案

您绝对应该首选默认参数值.

You should definitely prefer default parameter value.

  1. 您永远不应创建或使用诸如IntString之类的常规类型的隐式参数.请参见下面的引文.
  2. 默认值是最简单的解决方案.就语言功能而言,很复杂.
  3. 隐式参数用于您的方法的某种上下文".如果没有上下文,则只需使用默认值即可使其他开发人员感到困惑.
  4. 隐式值搜索将花费您一些编译时间.
  5. 仅在极少数情况下才应手动指定隐式参数.
  1. You should never create or use implicit parameters of general types like Int or String. See citation below.
  2. Default value is the simplest solution. In terms of language features complexity.
  3. Implicit parameters are for some kind of "context" for your method. If there is no context, just default value you can confuse other developers.
  4. Implicit value search will cost you some amount of compilation time.
  5. Implicit parameters should be specified manually only in rare cases.

另请参见:在Scala 21.5中编程隐式参数/一种样式隐式参数的规则:

作为样式规则,最好在隐式参数的类型中使用自定义命名类型.

As a style rule, it is best to use a custom named type in the types of implicit parameters.

这篇关于隐式参数VS默认参数值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆