【问题标题】:Scala named and default arguments in conjunction with implicit parametersScala 命名参数和默认参数以及隐式参数
【发布时间】:2012-03-14 01:51:24
【问题描述】:

考虑以下几点:

def f(implicit a: String, y: Int = 0) = a + ": " + y
implicit val s = "size"
println(f(y = 2))

最后一个表达式导致以下错误:

not enough arguments for method f: (implicit a: String, implicit y:
Int)java.lang.String. Unspecified value parameter a.

但是,如果您为隐式参数 a 提供默认值,则没有问题:

def f(implicit a: String = "haha!", y: Int = 0) = a + ": " + y
implicit val s = "size"
println(f(y = 2))

但最后一行打印出来

haha!: 2

虽然我已经预料到了

size: 2

所以隐含值's'没有被拾取。如果您不向 f 提供任何参数而只是调用

println(f)

然后隐式值被拾取,你得到

size: 0

有人能解释一下这里发生了什么吗?

【问题讨论】:

    标签: scala default-value named-parameters implicits


    【解决方案1】:

    试试

    println(f(y = 2, a = implicitly))
    

    一旦开始指定参数,就无法返回。要么是整个列表是隐含的,要么不是。

    【讨论】:

      【解决方案2】:

      隐式参数应该分开——首先,然后在方法定义的末尾——其次。像这样:

      def f(y: Int = 0)(implicit a: String) = a + ": " + y
      implicit val s = "size"
      println(f(y = 2))
      

      输出

      size: 2
      

      【讨论】:

      • 使用第一个默认参数必须调用f()
      【解决方案3】:

      按照 jsuereth 所说的,您可以将函数定义为

      def f(a: String = implicitly, y:Int = 0) = a + ": " + y
      

      或者以我更习惯的方式,

      def f(y:Int = 0)(implicit a: String) = a + ": " + y
      

      【讨论】:

      • 您应该检查隐式使用的隐式范围。我不认为它与第二个选项相同。
      猜你喜欢
      • 2011-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-14
      相关资源
      最近更新 更多