我有scala函数,如下所示,
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()
我想传递第三个参数作为隐式参数,但对于函数来说似乎不可能。
这是我想要的方法,
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()
由于apply
函数是预定义的,因此无法获得额外的接受隐式参数。
scala> new Function2[String, String, Seq[String]] {
def apply(user: String, apiToken: String): Seq[String] = Seq.empty
}
val res4: (String, String) => Seq[String] = <function2>
重载也不起作用,
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()
是不是implicit
根本不建议用于功能,或者我错过了什么?
答案 0 :(得分:1)
实验,你的函数可能表达如下,没有隐含的:
scala> def getOrders: (String, String) => (String) => Seq[String] = (user: String, apiToken: String) => (clientType: String) => Seq.empty[String]
def getOrders: (String, String) => String => Seq[String]
四处寻找......它不像implicit
那样可能会让你想要你想要的东西。
对related question的回答表明原因:getOrders
&#34; ...是方法,而不是函数,并且不会尝试eta-expansion(将方法转换为函数)直到隐式申请之后。&#34;似乎implicits在方法级别解决,而不是在函数级别解决。