更新时间:2022-12-14 14:00:49
彼得·施密茨(Peter Schmitz)简单地删除val
的解决方案(以及希望将RichElapsed
转换为值类的方法)当然是最简单且干扰最小的要做.
Peter Schmitz's solution to simply drop the val
(along with the hope of turning RichElapsed
into a value class) is certainly the simplest and least intrusive thing to do.
如果您确实感觉需要值类,那么另一种选择是:
If you really feel like you need a value class, another alternative is this:
class RichElapsed[A](val f: () => A) extends AnyVal {
def elapsed(): (A, Double) = {
val start = System.nanoTime()
val res = f()
val end = System.nanoTime()
(res, (end-start)/1e6)
}
}
implicit def toRichElapsed[A]( f: => A ) = new RichElapsed[A](() => f )
请注意,虽然使用上面的值类可以删除临时RichElapsed
实例的实例化,但仍然存在一些包装操作(包括我的解决方案和Peter Schmitz的解决方案).
即,将以名称传递为f
的主体包装到一个函数实例中(在Peter Schmitz的情况下,这在代码中并不明显,但无论如何都将在后台进行).
如果您也想删除此包装,我相信唯一的解决方案是使用宏.
Note that while using a value class as above allows to remove the instantiation of a temporary RichElapsed
instance, there is still some wrapping going on (both with my solution and with Peter Schmitz's solution).
Namely, the body passed by name as f
is wrapped into a function instance (in Peter Schmitz's case this is not apparent in the code but will happen anyway under the hood).
If you want to remove this wrapping too, I believe the only solution would be to use a macro.