省略一些隐式参数 [英] leaving out some implicit parameters

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

问题描述

是否可以省略一些隐式参数,但不是全部?我尝试使用命名参数:

Is it possible to leave out some implicit parameters but not all of them? I tried with named parameters:

def foo(implicit a: Int, b: String) {
  if (a > 0) {
    println(b)
    foo(a = a-1)   // error
  }
}

不幸的是,编译器使用以下命令拒绝了foo的递归调用:

Unfortunately, the compiler rejects the recursive call of foo with:

not enough arguments for method foo
Unspecified value parameter b

推荐答案

不可能遗漏一些隐式参数.因此,在您的示例中

It is not possible to leave out some implicit parameters. So, in your example

def foo(implicit a: Int, b: String): Unit = ???

不能仅指定a.但是,您可以指定隐式参数的默认值,例如

It is not possible to only specify a. However, you can specify the default value of the implicit parameter, for example

def foo(implicit a: Int, b: String = "---"): Unit = ???

如果b不是隐式可用的,将使用"---".

Where if b is not implicitly available, "---" will be used.

请记住,implicit关键字将参数列表标记为隐式,而不是将一个参数标记为隐式.

Remember that the implicit keyword marks the parameter list as implicit, not that one parameter as implicit.

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

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