使用宏扩展元素上的类型类操作
-
21-12-2019 - |
题
假设以下设置:
trait A[L] { def op(l1:L, l2:L): L }
trait E[L] { def op(l:L): L }
implicit def some2E[L:A](self:L) = new E[L] { def op(other:L) =
implicitly[A[L]].op(self,other) }
有没有办法直接扩展 m op n
到 a.op(m,n)
, ,在这样的背景下 a
是适当的隐式 A
, ,使用宏或至少避免额外的对象创建?
解决方案
如果将隐式参数移至 op
方法中,您可以使用值类来防止额外的对象创建:
implicit class some2E[L](val self: L) extends AnyVal {
def op(other: L)(implicit x: A[L]) = x.op(self, other)
}
热点可能会将调用内联到op
定义于 some2E
, ,所以你最终会得到 a.op(m, n)
.
不隶属于 StackOverflow