Scala-如何将隐式参数传递到函数(HOF)?
我有这样一个函数:Scala-如何将隐式参数传递到函数(HOF)?,scala,implicit,higher-order-functions,Scala,Implicit,Higher Order Functions,我有这样一个函数: def getSomething: (String, Future[String]) => String = { case (name, surname) if (name == "Joe", surname.map(s => s == "Doe")) => "Is ok" } 但编译器说他需要executionContext在map函数中。我试着用以下方法来变魔术: def getSomething (implicit e: ExecutionC
def getSomething: (String, Future[String]) => String = {
case (name, surname) if (name == "Joe", surname.map(s => s == "Doe")) => "Is ok"
}
但编译器说他需要executionContext
在map
函数中。我试着用以下方法来变魔术:
def getSomething (implicit e: ExecutionContext): (String, Future[String]) => String{...}
或
但它不起作用。是否可以将隐式参数传递给这样的函数?或者我可以用另一种方式吗
def getSomething (implicit e: ExecutionContext): (String, Future[String]) => String = ...
应该有用
你不会写字
(String, Future[String]) => (implicit e: ExecutionContext) => String
隐式函数将出现在Scala 3中
例如,在Scala 3中,我们可以返回带有隐式参数的函数
def getSomething: ExecutionContext ?=> Future[String] => Future[Int] = {
(using ec: ExecutionContext) => (f: Future[String]) => f.map(_.toInt)
}
given fiveThreadsEc as ExecutionContext = ExecutionContext.fromExecutor(Executors.newFixedThreadPool(5))
getSomething(Future("42"))
注意函数类型中的?=>
如何与函数文本中使用的相对应。从中考虑例子
说“它不工作”是不够的,在你的问题中添加错误信息<代码>定义getSomething(隐式e:ExecutionContext):…=代码>应该起作用。如果(name==“Joe”,姓氏.map(s=>s==“Doe”)
是什么<代码>如果接受的是布尔值
,而不是元组。接收未来而不返回未来的函数是代码气味。
def getSomething: ExecutionContext ?=> Future[String] => Future[Int] = {
(using ec: ExecutionContext) => (f: Future[String]) => f.map(_.toInt)
}
given fiveThreadsEc as ExecutionContext = ExecutionContext.fromExecutor(Executors.newFixedThreadPool(5))
getSomething(Future("42"))
val f: Int ?=> Int = (using x: Int) => 2 * x
f(using 2)