隐式函数的“类型”是什么?

2024-01-12

假设我有一个具有如下签名的函数:

 def tsadd(key: Any, time: Double, value: Any)(implicit format: Format): Option[Int]

我想创建其中一些函数的列表以供以后评估。我该怎么做。我尝试创建一个列表,例如:

val pipelineCmds:List[(String,Double,Any)(Format) => Option[Int]] = Nil

并这样做:

pipelineCmds ++ r.tsadd(symbol, timestamp.getMillis.toDouble, value)

但 val 没有很好地响应隐式参数格式。它期望在第一组括号后看到一个]。

最终目标是做类似的事情

r.pipeline { p => 
  pipelineCmds.foreach(c => p.c)
}

任何帮助是极大的赞赏!


据我所知,带有隐式参数的函数使用起来很烦人。适当的类型是(您的选择):

(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

但部分应用该功能效果不佳。您可以烦人地注释所有类型以获得最新版本:

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>

但将自己的代码写成任何你想要的形状并不困难:

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>

当然,如果您在创建列表时已经知道隐式值,则只需要类型

(String, Double, Any) => Option[Int]

然后你分配这样的功能

tsadd _
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

隐式函数的“类型”是什么? 的相关文章

随机推荐