What is "type" of a function with implict?
Let's say I have a function with a signature like this:
def tsadd(key: Any, time: Double, value: Any)(implicit format: Format): Option[Int]
And I want to create a list of some number of these functions for later evaluation. How do I do it. I tried creating a list l开发者_Go百科ike:
val pipelineCmds:List[(String,Double,Any)(Format) => Option[Int]] = Nil
and doing this:
pipelineCmds ++ r.tsadd(symbol, timestamp.getMillis.toDouble, value)
But the val didn't respond well the implicit param Format. It expects to see a ] after the first set of parens.
The ultimate goal is to do something like
r.pipeline { p =>
pipelineCmds.foreach(c => p.c)
}
Any help is greatly appreciated!
As far as I know, functions with implicit parameters are annoying to work with. The appropriate types are (your choice):
(String, Double, Any) => Format => Option[Int] // As written
Format => (String, Double, Any) => Option[Int] // Conceptually works more like this
String => Double => Any => Format => Option[Int] // Completely curried
(String, Double, Any, Format) => Option[Int] // Closest to how the JVM sees the method
but partial application of the function does not work well. You can annoyingly annotate all your types to get the last version:
class Format {} // So the example works
def tsadd(s: String, d: Double, a: Any)(implicit f: Format): Option[Int] = None
scala> tsadd(_: String, _: Double, _: Any)(_: Format)
res2: (String, Double, Any, Format) => Option[Int] = <function4>
but it's not much harder to write your own to be whatever shape you want:
def example(f: Format => (String, Double, Any) => Option[Int]) = f
scala> example(f => { implicit val fm=f; tsadd _ })
res3: (Format) => (String, Double, Any) => Option[Int] = <function1>
Of course, if you already know the implicit values when you're creating the list, you just need the type
(String, Double, Any) => Option[Int]
and you assign the functions like
tsadd _
scala> val pipelineCmds:List[(String,Double,Any) => Format => Option[Int]] = Nil
pipelineCmds: List[(String, Double, Any) => (Format) => Option[Int]] = List()
But note that the "implicitness" is lost from function values and you must explicitly pass in a format.
As @pst mentioned in a comment, even if you declared a list of the appropriate type, I don't know how you'd assign anything to it.
One solution is to use:
def tsadd(key: Any, time: Double, value: Any, format: Format): Option[Int]
with an explicit format
argument. You can put such tsadd
functions in a List[...]
as usual. Then to get the implicit format
behavior you want you add that to the wrapper:
def invoke_tsadd(list_selector: Whatever, key: Any, time: Double, value: Any)(implicit format: Format): Option[Int] =
selected_from_your_list(list_selector).tsadd(key, time, value, format)
精彩评论