How can I define a function with multiple implicit arguments.
def myfun(arg:String)(implicit p1: String)(implicit p2:Int)={} // doesn't work
Scala implicit allows you to omit calling method or parameter directly. For example, you can write a function that converts int to/from string explicitly but you can ask the compiler to do the same thing for you, implicitly.
Implicit parameters are the parameters that are passed to a function with implicit keyword in Scala, which means the values will be taken from the context in which they are called.
A method or constructor can have only one implicit parameter list, and it must be the last parameter list given. A method with implicit parameters can be applied to arguments just like a normal method.
What Are Implicit Parameters? Implicit parameters are similar to regular method parameters, except they could be passed to a method silently without going through the regular parameters list. A method can define a list of implicit parameters, that is placed after the list of regular parameters.
They must all go in one parameter list, and this list must be the last one.
def myfun(arg:String)(implicit p1: String, p2:Int)={}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With