Defining a function with multiple implicit arguments in Scala

后端 未结 3 1444
[愿得一人]
[愿得一人] 2021-01-30 12:36

How can I define a function with multiple implicit arguments.

def myfun(arg:String)(implicit p1: String)(implicit p2:Int)={} // doesn\'t work
3条回答
  •  再見小時候
    2021-01-30 13:03

    There actually is a way of doing exactly what the OP requires. A little convoluted, but it works.

    class MyFunPart2(arg: String, /*Not implicit!*/ p1: String) {
      def apply(implicit p2: Int) = {
        println(arg+p1+p2)
        /* otherwise your actual code */
      }
    }
    
    def myFun(arg: String)(implicit p1: String): MyFunPart2= {
      new MyFunPart2(arg, p1)
    }
    
    implicit val iString= " world! "
    implicit val iInt= 2019
    
    myFun("Hello").apply
    myFun("Hello")(" my friend! ").apply
    myFun("Hello")(" my friend! ")(2020)
    
    //  Output is:
    //      Hello world! 2019
    //      Hello my friend! 2019
    //      Hello my friend! 2020
    

    In Scala 3 (a.k.a. "Dotty", though this is the compiler's name) instead of returning an auxiliary MyFunPart2 object, it's possible to return a function value with implicit arguments directly. This is because Scala 3 supports "Implicit Functions" (i.e. "parameter implicitness" now is part of function types). Multiple implicit parameter lists become so easy to implement that it's possible the language will support them directly, though I'm not sure.

提交回复
热议问题