leaving out some implicit parameters

吃可爱长大的小学妹 提交于 2019-12-01 23:18:55

问题


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
  }
}

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

not enough arguments for method foo
Unspecified value parameter b

回答1:


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

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

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 = ???

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

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




回答2:


Not sure what you're trying to achieve, but something like this could do:

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


来源:https://stackoverflow.com/questions/17467203/leaving-out-some-implicit-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!