Scala 命名参数和默认参数与隐式参数结合使用
考虑以下内容:
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
Can 有人阐明这里发生的情况吗?
Consider the following:
def f(implicit a: String, y: Int = 0) = a + ": " + y
implicit val s = "size"
println(f(y = 2))
The last expression causes the following error:
not enough arguments for method f: (implicit a: String, implicit y:
Int)java.lang.String. Unspecified value parameter a.
However, if you provide a default value to the implicit parameter a, there is no issue:
def f(implicit a: String = "haha!", y: Int = 0) = a + ": " + y
implicit val s = "size"
println(f(y = 2))
But the last line prints
haha!: 2
while I would have expected
size: 2
So the implicit value 's' is not picked up. If you instead don't provide any parameters to f and just call
println(f)
then the implicit value is picked up and you get
size: 0
Can someone shed some light on what's going on here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
尝试
一旦开始指定参数,就无法返回。要么整个列表是隐式的,要么没有一个是隐式的。
Try
Once you start specifying parameters, you can't go back. It's either the whole list is implicit or none of it is.
隐式参数应该单独放置——首先,然后在方法定义的末尾——其次。像这样:
输出
Implicit parameters should go separately -- first, and in the end of method definition -- second. Like this:
Ouputs
按照 jsuereth 所说的,你可以将你的函数定义为
或者以我更习惯看到的方式,
Along the lines of what jsuereth said, you could define your function as
Or in the way I'm more used to seeing,