Expand type class operations on elements using macros
-
21-12-2019 - |
Question
Assuming the following setup:
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) }
Is there a way to directly expand m op n
to a.op(m,n)
, in a context where a
is the appropriate implicit A
, using macros or at least avoid the additional object creation?
Solution
If you move the implicit parameter to the op
method, you can use a value class to prevent the additional object creation:
implicit class some2E[L](val self: L) extends AnyVal {
def op(other: L)(implicit x: A[L]) = x.op(self, other)
}
Hotspot will probably inline the call to theop
defined in some2E
, so you will end up with a.op(m, n)
.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow