如何在trait中创建功能对象时传递隐式参数?
此代码无法编译。
my_RtlInitUnicodeString rtlInitUnicodeString ....
我希望做到这样的事情:
case class Cache(key: Int, value: String)
trait Processor {
val process = processF _ // error: could not find implicit value for parameter cache: Cache
private def processF()(implicit cache: Cache): String = cache.value
}
object Main extends App with Processor {
implicit val cache = Cache(10, "hello")
process()
}
或者有没有可用的方法?
答案 0 :(得分:0)
与方法不同,函数对象不能有隐式参数。
我认为
// in Processor
def process(implicit cache: Cache) = () => processF()
// in Main
process.apply()
// or
val process1 = process
process1()
最接近你想要的。可替换地,
trait Processor {
implicit val cache: Cache
val process = processF _ // error: could not find implicit value for parameter cache: Cache
private def processF(): String = cache.value
}