leaving out some implicit parameters

后端 未结 2 1496
陌清茗
陌清茗 2021-01-20 15:27

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         


        
相关标签:
2条回答
  • 2021-01-20 16:17

    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)
    }
    
    0 讨论(0)
  • 2021-01-20 16:20

    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.

    0 讨论(0)
提交回复
热议问题