prayagupadhyay
prayagupadhyay

Reputation: 31222

scala function with implicit parameters

I have scala function as below,

scala> def getOrders: (String, String) => Seq[String] = (user: String, apiToken: String) => Seq.empty[String] 
def getOrders: (String, String) => Seq[String]

scala> getOrders("prayagupd", "A1B2C3") 
val res0: Seq[String] = List()

I want to pass in a third parameter as a implicit parameter but it does not seem possible for a function.

Here's what I want achieved using a method,

scala> def getOrders(user: String, apiToken: String)(implicit clientType: String) = Seq.empty[String] 
def getOrders
  (user: String, apiToken: String)(implicit clientType: String): Seq[String]

scala> implicit val clientType: String = "android" 
implicit val clientType: String = "android"

scala> getOrders("prayagupd", "A1B2C3") 
val res2: Seq[String] = List()

It does not seem possible because of the fact that apply function is predefined, which won't extra accept implicit parameter.

scala> new Function2[String, String, Seq[String]] {
          def apply(user: String, apiToken: String): Seq[String] = Seq.empty
         } 
val res4: (String, String) => Seq[String] = <function2>

Overloadding does not do the trick either,

scala> new Function2[String, String, Seq[String]] {
          def apply(user: String, apiToken: String): Seq[String] = Seq.empty
          def apply(user: String, apiToken: String)(implicit clientType: String) = Seq("order1")
         } 
val res9: (String, String) => Seq[String] = <function2>

scala> implicit val clientType: String = "device" 
implicit val clientType: String = "device"

scala> res9("prayagupd", "apiToken") 
val res10: Seq[String] = List()

Is it that implicits are not recommended at all for functions or I'm missing something?

Upvotes: 1

Views: 100

Answers (1)

Richard Sitze
Richard Sitze

Reputation: 8463

Experimental, your function might be expressed as follows without the implicit:

scala> def getOrders: (String, String) => (String) => Seq[String] = (user: String, apiToken: String) => (clientType: String) => Seq.empty[String]
def getOrders: (String, String) => String => Seq[String]

Poking around on that... it doesn't like implicit anywhere in there that might give you want you want.

An answer to a related question suggests the reason: getOrders "... is a method, not a function, and eta-expansion (which converts methods to functions) is not attempted until after implicit application." It seems that implicits are resolved at a method level, not a function level.

Upvotes: 1

Related Questions