什么是“类型"?隐含的函数? [英] 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 like:
val pipelineCmds:List[(String,Double,Any)(Format) => Option[Int]] = Nil
并这样做:
pipelineCmds ++ r.tsadd(symbol, timestamp.getMillis.toDouble, value)
但是 val 没有很好地响应隐式参数格式.它希望在第一组括号之后看到一个 ].
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)
}
非常感谢任何帮助!
推荐答案
据我所知,带有隐式参数的函数使用起来很烦人.适当的类型是(您的选择):
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]
然后你分配像
tsadd _
这篇关于什么是“类型"?隐含的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!