Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining a function with multiple implicit arguments in Scala

Tags:

scala

How can I define a function with multiple implicit arguments.

def myfun(arg:String)(implicit p1: String)(implicit p2:Int)={} // doesn't work 
like image 763
Ali Salehi Avatar asked May 17 '12 12:05

Ali Salehi


People also ask

How does Scala define implicit function?

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.

What is implicit argument in Scala?

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.

How many implicit parameters can an instance method have?

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?

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.


2 Answers

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)={}  
like image 142
missingfaktor Avatar answered Oct 30 '22 13:10

missingfaktor


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.

like image 24
Mario Rossi Avatar answered Oct 30 '22 11:10

Mario Rossi